在Redux中反应路由器路由参数

时间:2016-11-02 04:20:04

标签: javascript reactjs redux react-router react-router-redux

使用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 个答案:

答案 0 :(得分:3)

如果要访问组件内部的路由器参数,使用 withRouter

实现此目的的最佳方法

https://egghead.io/lessons/javascript-redux-using-withrouter-to-inject-the-params-into-connected-components

您将通过上述示例找到更好的理解。

答案 1 :(得分:2)

如果您想访问redux商店中的路由器,则会有一个名为withRouterdocs)的HOC。如果我没记错的话,这会将任何路由器状态作为道具传递给你的组件。

您需要对组件进行的唯一更改是:

import { withRouter } from 'react-router'

export default withRouter(ReportViewerContainer);

答案 2 :(得分:1)

所以我认为您可以使用context来获取将通过路由器传递的位置。 (请参阅有关其工作原理的链接。)这应该为您提供一个可靠的方向。

这也可以帮助您顺利使用国际化

class MyComponent extends React.Component {
    static contextTypes = {
        router: React.PropTypes.object
    };

    render(){
        // By declaring context type here, and childContextTypes
        // on the parent along with a function with how to get it,
        // React will traverse up and look for the `router` context.
        // It will then inject it into `this.context`, making it 
        // available here.
    }
}
相关问题