使用redux和react路由器,我想访问除路由指定的组件之外的组件的路由参数 .
我已经设置了react-router,redux和react-router-redux,如下所示,我想从我的redux商店访问reportId参数 .
const history = syncHistoryWithStore(browserHistory, store);
const store = createStore(reducers);
const routes = (
<Router history={history}>
<Route path="/" component={MainLayout} >
<IndexRoute component={Home} />
<Route path="reports">
<Route path=":reportId" component={ReportViewerContainer} />
</Route>
</Route>
</Router>
);
ReactDOM.render(
<Provider store={store}>{router}</Provider>,
document.getElementById('root')
);
我已经尝试连接react-redux-router来存储路由状态,但我发现除了活动路由的完整路径之外,还没有任何有用的存储在redux内部 . 这让我可以选择从redux中的路径解析reportId,或者在redux中创建我自己的自定义操作,并使用我的ReportViewerContainer组件内的componentWillReceiveProps生命周期方法更新它 . 肯定有更好的办法?
3 回答
如果要访问组件内部的router参数,请使用 withRouter 实现此目的的最佳方法
https://egghead.io/lessons/javascript-redux-using-withrouter-to-inject-the-params-into-connected-components
通过上面的例子你会发现更好的理解 .
如果要访问redux存储中的路由器,则会有一个名为
withRouter
(docs)的HOC . 如果我没记错的话,这会将任何路由器状态作为道具传递给您的组件 .您需要对组件进行的唯一更改是:
所以我认为你可以使用context来获取将通过路由器传递的位置 . (请参阅有关其工作原理的链接 . )这应该为您提供一个可靠的方向 .
这也可以帮助您顺利完成国际化工作 .