【问题标题】:React Router Route Params in ReduxRedux 中的 React Router 路由参数
【发布时间】:2023-03-12 16:40:02
【问题描述】:

使用 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 生命周期方法对其进行更新。一定有更好的办法吗?

【问题讨论】:

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


    【解决方案1】:

    如果你想访问组件内部的路由参数,最好的方法是使用withRouter

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

    通过上面的例子你会发现更好的理解。

    【讨论】:

      【解决方案2】:

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

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

      import { withRouter } from 'react-router'
      
      export default withRouter(ReportViewerContainer);
      

      【讨论】:

        【解决方案3】:

        所以我认为您可以使用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.
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2016-09-02
          • 2020-08-13
          • 2020-09-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-26
          • 2016-05-12
          • 2019-01-22
          相关资源
          最近更新 更多