【问题标题】:How use redux state with routes react-router?如何将 redux 状态与路由 react-router 一起使用?
【发布时间】:2023-03-17 20:53:02
【问题描述】:

我创建了我的路线

<Provider store={store}>
    <Router history={browserHistory}>
        <Route path="/" component={App}>
        <Route path="/redux" component={redux} />
    </Router>
</Provider>

我的问题是当我从 redux 组件调度一个动作时,道具在 /redux 路由中发生了变化,但在 / 始终是初始状态。请问谁能帮帮我?

【问题讨论】:

    标签: react-router react-redux


    【解决方案1】:

    尝试使用react-router-redux (https://github.com/reactjs/react-router-redux) 将redux 存储与react-router 同步。

    import { browserHistory } from 'react-router';
    import { syncHistoryWithStore, routerReducer } from 'react-router-redux';
    import { createStore, combineReducers } from 'redux';
    
    // Add router reducer to your store on the `routing` key
    const store = createStore(
      combineReducers({
        ...reducers,
        routing: routerReducer
      })
    )
    // Create enhanced history that syncs navigation events with the store
    const history = syncHistoryWithStore(browserHistory, store);
    
    ...
    
    <Provider store={store}>
        <Router history={history}>
            <Route path="/" component={App}>
            <Route path="/redux" component={redux} />
        </Router>
    </Provider>
    

    【讨论】:

    • 我必须添加此代码,否则我还必须编辑我的减速器?
    • 对不起,您还需要将路由器减速器添加到您的商店。我已经更新了我的答案。
    • 我只有一个减速器叫做 .我这样做了`const store = createStore(combineReducers({ myreducer, routing: routerReducer })`,我得到一个错误,reducer undefined :()
    • 这里是我的完整代码stackoverflow.com/questions/47290038/…
    • 请仔细检查您是否正确导入了react-router-redux,并将正确的数据传递给combineReducers 方法。 combineReducers 方法需要一个对象作为参数。
    猜你喜欢
    • 2021-12-01
    • 2018-07-28
    • 1970-01-01
    • 2016-06-10
    • 2018-02-03
    • 2016-09-23
    • 2016-02-04
    • 2018-08-11
    • 2017-02-19
    相关资源
    最近更新 更多