【问题标题】:Redux app state via url -> query paramRedux 应用程序状态通过 url -> 查询参数
【发布时间】:2016-04-20 20:47:54
【问题描述】:

使用https://github.com/reactjs/react-router-redux/

如果我想根据 url 查询参数重新加载应用程序 (Redux) 状态,那么通过获取 state.routing.locationBeforeTransitions.query 属性来做到这一点的正确方法是什么?

它有效......只是想知道这是否是正确的方法。

【问题讨论】:

    标签: reactjs redux react-router-redux


    【解决方案1】:

    使用 Redux 连接组件,您可以从 mapStateToProps 的第二个参数访问路由器的道具:

    function mapStateToProps (state, ownProps) {
      return {
        num: state.items.num,
        query: ownProps.location.query
      }
    }
    
    export default connect(mapStateToProps, null)(YourComponent)
    

    见https://github.com/reactjs/react-router-redux#user-content-how-do-i-access-router-state-in-a-container-component。

    您也可以在这里查看演示 https://github.com/timarney/react-router-redux-query-params。

    【讨论】:

      【解决方案2】:

      来自docs:

      您不应该直接从 Redux 存储中读取位置状态。这是因为 React Router 是异步操作的(用于处理诸如动态加载的组件之类的事情),并且您的组件树可能尚未与您的 Redux 状态同步更新。你应该依赖 React Router 传递的 props,因为它们只有在处理完所有异步代码后才会更新。

      正确的方法在文档中,但您只能在路由组件中执行此操作(那些您放入 <Route path='/' component={Component} /> 的组件)。

      如果我想在某个内部组件中访问它,我通常会传递 location 属性。

      【讨论】:

        猜你喜欢
        • 2016-08-04
        • 1970-01-01
        • 2018-05-13
        • 1970-01-01
        • 2017-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-03
        相关资源
        最近更新 更多