获取 actioncreator/selector 内的路由参数?
Get route params inside actioncreator/selector?
使用 redux 路由器,在我的组件中,我可以访问包含 URL.
相关信息的 params
对象
然而,在我的actioncreators中,我通过getState()
获取状态,因此没有注入params道具。
有解决办法吗?
要在 action creators 中获取访问参数,您应该传递它:
在组件中
this.props.someAction(this.props.params)
在行动创造者
const someAction = (params)=>{
let {data} = params;
....
}
要在选择器中获取访问参数,您应该传递它:
在组件中
const mapStateToProps=(state, ownProps)=({
data:someSelector(state,ownProps.params)
})
在选择器中
const someSelector=(state, params)={
..some computing
return result
}
从 getState() 访问路由器的参数、路径名和查询:
您需要安装redux-router
如果您已经在使用它,请检查
1.routes
import { ReduxRouter } from 'redux-router';
<Provider store={store}>
<ReduxRouter>
<Route path="/" component={App}>
//...routes
</Route>
</ReduxRouter>
</Provider>
2.reducer
import { routerStateReducer } from 'redux-router';
const reducer = combineReducers({
router: routerStateReducer,
...
});
3.store 魔法师
import { reduxReactRouter} from 'redux-router';
import { createHistory } from 'history';
import { compose, createStore, applyMiddleware } from 'redux';
const store = compose(
applyMiddleware(m1, m2, ...),
reduxReactRouter({
createHistory
})
)(createStore)(reducer);
使用 redux 路由器,在我的组件中,我可以访问包含 URL.
相关信息的params
对象
然而,在我的actioncreators中,我通过getState()
获取状态,因此没有注入params道具。
有解决办法吗?
要在 action creators 中获取访问参数,您应该传递它:
在组件中
this.props.someAction(this.props.params)
在行动创造者
const someAction = (params)=>{
let {data} = params;
....
}
要在选择器中获取访问参数,您应该传递它:
在组件中
const mapStateToProps=(state, ownProps)=({
data:someSelector(state,ownProps.params)
})
在选择器中
const someSelector=(state, params)={
..some computing
return result
}
从 getState() 访问路由器的参数、路径名和查询:
您需要安装redux-router
如果您已经在使用它,请检查
1.routes
import { ReduxRouter } from 'redux-router';
<Provider store={store}>
<ReduxRouter>
<Route path="/" component={App}>
//...routes
</Route>
</ReduxRouter>
</Provider>
2.reducer
import { routerStateReducer } from 'redux-router';
const reducer = combineReducers({
router: routerStateReducer,
...
});
3.store 魔法师
import { reduxReactRouter} from 'redux-router';
import { createHistory } from 'history';
import { compose, createStore, applyMiddleware } from 'redux';
const store = compose(
applyMiddleware(m1, m2, ...),
reduxReactRouter({
createHistory
})
)(createStore)(reducer);