【问题标题】:Confusion react-router-dom and react-router-redux混淆 react-router-dom 和 react-router-redux
【发布时间】:2018-02-25 23:51:18
【问题描述】:

我是 react 和 redux 的新手,我的项目是用 react-router-dom 开始的,现在我想在组合中添加 Redux。

我应该继续使用 react-router-dom 还是只安装 react-router-redux?或两者? Route 组件的工作方式是否相同?我有点困惑 react-router-dom 的用途是什么?

我是否将所有的 Link 组件切换到一个向商店分派操作的 a 元素?

感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:

    一般在使用Redux的时候,推荐使用react-router-redux,它封装了react-router。

    只有在你初始化你的应用程序时,你才应该从 react-router 向 Redux 传递一些东西,它们是 RouterbrowserHistory

    在 app.js 中:

    import { Router, browserHistory } from 'react-router';
    import { syncHistoryWithStore } from 'react-router-redux';
    
    const initialState = {};
    const store = configureStore(initialState, browserHistory);
    
    const history = syncHistoryWithStore(browserHistory, store);
    
    const render = () => {
      ReactDOM.render(
        <Provider store={store}>
            <Router
              history={history}
              routes={rootRoute}
            />
        </Provider>,
        document.getElementById('app')
      );
    };
    

    您将 react 的 Router 元素作为 Redux 的 Provider 元素的子元素提供,并且您还向 Router 元素提供了 React 的 browserHistory 的 Redux 包装器。

    在你项目的其余部分,你只需要使用react-router-redux,而不是直接调用React。

    react-router-dom BTW 只是 React 4 中的另一层简化,它封装了 react-router,但是如果你的项目架构是 Redux,那么你需要按照 Redux 的规则工作,因此只使用 react- router-redux 以便在每个 action 中通过 store(除了前面提到的初始化)。

    【讨论】:

    【解决方案2】:

    使用 react-router-redux。

    使用 react-router-redux,位置状态作为普通对象保存在您的 redux 存储中。这意味着您可以像在任何其他状态下一样使用 connect 注入位置信息。

    【讨论】:

      【解决方案3】:

      我会推荐你​​使用 react-router-redux。 使用 react-router-redux 你可以将你的路由器状态与你的 Redux Store 连接起来,这样你就可以使用你用来与应用程序状态交互的相同 API 与路由器交互。

      【讨论】:

        猜你喜欢
        • 2017-10-04
        • 2017-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-16
        • 1970-01-01
        • 2020-07-05
        • 2019-07-14
        相关资源
        最近更新 更多