【问题标题】:Redux connect "blocks" navigation with react-router-reduxRedux 使用 react-router-redux 连接“块”导航
【发布时间】:2018-10-16 09:28:58
【问题描述】:

在使用 reactreduxreact-router 的应用程序中,我使用的是 react-router-redux em> 发出导航操作。我发现使用 connect 将路由包装在组件中会阻止导航。

我使用 CodeSandbox 制作了一个示例来说明问题:sample

按原样,导航不起作用。但是,如果在 ./components/Routes.jsx 中,这一行:

export default connect(() => ({}), () => ({}))(Routes);

替换为:

export default Routes;

有效。

知道如何在组件中使用 connect 来包装路线而不破坏导航吗?

【问题讨论】:

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


    【解决方案1】:

    你有没有遇到过警告信息:

    Warning: You cannot change <Router history>

    使用withRouter from react-router-dom

    我已经搜索了很长时间,因为 Redux 正在重新创建我的 App.jsx 组件,该组件具有 <Route> </Route> 作为父级,并且此警告只会冻结我的应用程序中的路由。我想要 React/Redux 组件,因为我需要将 authenticated 属性传递给 Route 组件,并基于它进行重定向,很简单。

    所以import { withRouter } from 'react-router-dom'

    并围绕连接到 redux 的组件:

    export default withRouter(connect(mapStateToProps)(App));

    更多: 大多数情况下,如果您想与路由器通信,获取一些道具,向其传递其他内容,获取历史记录,形成它的位置,并且您在应用程序中使用 Redux,使用 withRouter 包围此组件,您将可以访问将这些属性作为道具。

    【讨论】:

      【解决方案2】:

      无意重复。

      我像这样用withRouter 修复了它

      import { withRouter } from 'react-router-dom';
      

      export default withRouter( connect(mapStateToProps)(App) );
      

      请参阅 Redux、路由器集成文档here

      【讨论】:

        【解决方案3】:

        请参阅 react-redux 文档中的 troubleshooting 部分。

        如果您将 Routes.jsx 导出更改为:

        export default connect(() => ({}), () => ({}), null, { pure: false })(Routes);
        

        它会起作用的。

        这是因为connect()默认实现了shouldComponentUpdate, 假设您的组件将产生相同的结果给定 相同的道具和状态。

        路线改变,但道具不改变,因此视图不会更新。

        您可以使用withRouter hoc 实现相同的效果。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-09-28
          • 2017-11-17
          • 2018-06-06
          • 1970-01-01
          • 1970-01-01
          • 2018-04-08
          • 2016-08-14
          相关资源
          最近更新 更多