【问题标题】:async reducer with react-router seems to have multiple stores?带有 react-router 的异步减速器似乎有多个商店?
【发布时间】:2017-04-07 09:41:29
【问题描述】:

我有一个异步减速器结构。在任何给定页面上,我将页面的 reducer 注入:

export const injectReducer = (store, { key, reducer }) => {
  // store.asyncReducers already initialized to {}
  // makeRootReducer just returns combineReducers({...store.asyncReducers})

  store.asyncReducers[key] = reducer
  store.replaceReducer(makeRootReducer(store.asyncReducers))
} 

我在任何给定页面上使用react-router 3 和普通路由定义。我使用require.ensure 对普通路由定义的getComponent 内的路由进行异步处理:

export default (store) => ({
  path : 'counter',
  getComponent (nextState, cb) {
    require.ensure([], (require) => {

      const Counter = require('./containers/Counter').default
      const reducer = require('./modules/counter').default

      injectReducer(store, { key: 'counter', reducer })

      cb(null, Counter)

    }, 'Counter')
  }
})

我的问题是,如果我使用dispatch 后跟browserHistory.push,我希望状态在进入新页面之前得到更新。然而,发生的事情是似乎有 2 家独立的商店。例如,在页面之间导航,上一页的计数器的值似乎被保留,尽管它位于同一个键上。这是怎么回事???

我的问题的示例repo。您可以git clonenpm installnpm start 并转到localhost:3000/counter。如果您单击Double (Async),它会将计数器加倍,然后转到/otherPage。如果您随后单击Half (Async),它将带您回到/counter。但是计数器的值是来自doubling 的值,而不是来自halving 的值。此外,重要的是,拉起Redux DevTools 并在页面之间导航似乎显示了之前所有数据的计数器更改。几乎就像整个商店都被替换了一样,但保留了先前的值。

这是怎么回事???

【问题讨论】:

    标签: redux redux-thunk


    【解决方案1】:

    经过大量调查,我发现在开发中 ReduxDevTools 将在新页面上重新计算整个状态历史。在新页面上插入一个新的 reducer,其中 initialState 不同会导致 2 个不同的结果。没有 2 个 store 或任何缓存,它只是 redux 开发工具用不同的 initialStates 重新计算整个状态历史。

    因此,在我的场景中,调度正在更新我第一页上的状态。然后 browserHistory 推送到第二页。第二页重新计算整个状态历史。但是,第二页有一个 reducer,它缺少第一页的操作处理程序。因此,当重新计算整个状态历史时,状态不会从最后一个动作发生变化。

    【讨论】:

      猜你喜欢
      • 2019-09-17
      • 1970-01-01
      • 2020-07-04
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 2016-10-25
      • 2023-03-06
      • 1970-01-01
      相关资源
      最近更新 更多