从boilerplate中学到的redux里replaceReducer的按需使用

脚手架代码

  const store = createStore(
makeRootReducer(),
initialState,
compose(
applyMiddleware(...middleware),
...enhancers
)
)
store.asyncReducers = {}

export const makeRootReducer = (asyncReducers) => {
return combineReducers({
...asyncReducers
})
}

export const injectReducer = (store, { key, reducer }) => {
store.asyncReducers[key] = reducer
store.replaceReducer(makeRootReducer(store.asyncReducers))
}

export default makeRootReducer

基本解释

  1. 创建store的时候reducer是空的
  2. asyncReducers可以随时被注入某一个reducer
  3. 注入后会 替代当前store的reducer

具体应用

某路由

import { injectReducer } from '../../store/reducers'

export default (store) => ({
path: 'counter/:id',
/* Async getComponent is only invoked when route matches */

getComponent(nextState, cb) {
/* Webpack - use 'require.ensure' to create a split point
and embed an async module loader (jsonp) when bundling */
require.ensure([], (require) => {
/* Webpack - use require callback to define
dependencies for bundling */
const Counter = require('./containers/CounterContainer').default
const reducer = require('./modules/counter').default

/* Add the reducer to the store on key 'counter' */
injectReducer(store, { key: 'counter', reducer })
// console.log(store);
/* Return getComponent */
cb(null, Counter)

/* Webpack named bundle */
}, 'counter')
}
})

路由里动态require自己的组件和reducer,然后注入到store并且替换的reducer

为毛?

为毛要注入reducer并且replace?

关键词

  • 按需

难道按照教程那种几个reducer合成combineReducer,放到createStore里就不按需么
答案是肯定的

要清楚理解这个注入replace的秒处,首先大家需要看看redux的源码

当你想处理某个action或者变动store的时候,大致顺序是这样的

  1. 你要dispatch了
  2. dispatch会把action 轮询combineReducer里的每一个reducer去找那个对应的type
  3. 然后变更store
  4. 最后你得到了

第二步:败笔
如果你有n多reducer,每一个都switch一下,经过了好多判断才找到你的目标。这能说是按需么

replace的效果
这个注入replace的过程就是初始reducer为空,当你进入某个路由的时候,你需要明确注入你需要的reducer。
这样当前这一时刻的store里所有存在的reducer都是你可能用到了。不存在完全无用的reducer,也就减少了无用的循环和判断