reducer 拆分后,和组件是一一对应的。我们就希望在做按需加载的时候,reducer也可以跟着组件在必要的时候再加载,然后用新的 reducer 替换老的 reducer。

    1. const createStore = function (reducer, initState) {
    2. ...
    3. function replaceReducer(nextReducer) {
    4. reducer = nextReducer
    5. /*刷新一遍 state 的值,新来的 reducer 把自己的默认状态放到 state 树上去*/
    6. dispatch({ type: Symbol() })
    7. }
    8. ...
    9. return {
    10. ...
    11. replaceReducer
    12. }
    13. }

    我们来尝试使用下

    1. const reducer = combineReducers({
    2. counter: counterReducer
    3. });
    4. const store = createStore(reducer);
    5. /*生成新的reducer*/
    6. const nextReducer = combineReducers({
    7. counter: counterReducer,
    8. info: infoReducer
    9. });
    10. /*replaceReducer*/
    11. store.replaceReducer(nextReducer);

    replaceReducer 示例源码见 demo-5