使用 combineReducers 未定义 Redux 预加载状态

Redux preloaded state is undefined with combineReducers

我正在使用 Redux,我有以下代码:

const initialState = {
  foo: "foo",
};

const store = createStore(
  rootReducer,
  initialState
);

...

const rootReducer = combineReducers({,
  foo: (state) => {
    console.log(state);
    return state;
  },
});

根据the documentation

With combineReducers() the behavior is more nuanced. Those reducers whose state is specified in preloadedState will receive that state. Other reducers will receive undefined and because of that will fall back to the state = ... default argument they specify.

我希望我的情况是前者,因此我希望我的减速器将 "foo" 记录到控制台,但我得到的是 undefined,然后导致应用程序失败,因为“键“foo”的切片缩减程序在初始化期间返回未定义”。我错过了什么?

顺便说一句,我知道我可以在 fooReducer 中设置一个默认值来处理这种情况(即设置 (state = someInitialState)),但我的问题是:我是否被迫这样做?因为根据文档我不应该。

编辑

这是该问题的一个工作示例:

const rootReducer = Redux.combineReducers({
  foo: (state) => {
    console.log(`State is: ${state}`);
    return state;
  }
});

const initialState = {
  foo: 'initialFooValue',
};

try {
  const store = Redux.createStore(rootReducer, initialState);
} catch (error) {
  console.error(error);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.2.0/redux.js"></script>

我想你在这里遗漏的事实是,当你使用 combineReducers 时,每个减速器都需要自己的 initial value,请检查此代码以了解我的意思:

const initialFoo = 'initialFooValue';

const initialState = {
  foo: 'anotherValue',
};

const FooReducer = (state = initialFoo) => {
    console.log(`State is: ${state}`);
    return state;
  }

const rootReducer = Redux.combineReducers({
  foo: FooReducer
});


try {
  const store = Redux.createStore(rootReducer, initialState);
  console.log('see the store structure', store.getState());
} catch (error) {
  console.error(error);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.2.0/redux.js"></script>