reducer 拆分后,和组件是一一对应的。我们就希望在做按需加载的时候,reducer也可以跟着组件在必要的时候再加载,然后用新的 reducer 替换老的 reducer。
const createStore = function (reducer, initState) {
...
function replaceReducer(nextReducer) {
reducer = nextReducer
/*刷新一遍 state 的值,新来的 reducer 把自己的默认状态放到 state 树上去*/
dispatch({ type: Symbol() })
}
...
return {
...
replaceReducer
}
}
我们来尝试使用下
const reducer = combineReducers({
counter: counterReducer
});
const store = createStore(reducer);
/*生成新的reducer*/
const nextReducer = combineReducers({
counter: counterReducer,
info: infoReducer
});
/*replaceReducer*/
store.replaceReducer(nextReducer);
replaceReducer 示例源码见 demo-5