在redux中,使用combineReducers预加载状态

时间:2017-02-15 05:09:50

标签: javascript reactjs redux react-redux reducers

我刚刚介绍了redux,并且我一直处于预加载状态的问题。

当使用单个reducer时,我使用以下代码,它曾经工作正常。相关网页摘要::

const head = (state = {}, action) => {
 switch (action.type) {

  case 'TOGGLE_VISIBLITY':
    if (state.head.content !== action.id) {
      return state
    }
    state.body.visible = !state.body.visible;
    return state;

    default:
      return state
    } 
 }

const heads = (state = [], action) => {
   switch (action.type) {
      case 'TOGGLE_VISIBLITY':
  state.body = state.body.map(t =>
    head(t, action)
  );
 }
 return state;
}

export const store = createStore(heads, config);

但是我改为使用了combinerReducers,它开始引发JS错误。

  

在preloadedState参数中发现的意外键“head”,“body”传递给createStore。预计会找到一个已知的减速器键:“head”。意外的密钥将被忽略。

我的改变是::

const plannerApp = combineReducers({
   heads
});

export const store = createStore(plannerApp, config);

如果您想查看完整代码,请访问here

任何帮助都非常值得赞赏。非常感谢提前..我感谢你的时间和努力...

1 个答案:

答案 0 :(得分:3)

简而言之,预加载状态需要与减速器的结构相匹配。由于您切换到使用combineReducers,因此您的状态树结构已更改。您现在拥有heads的顶级密钥,其子密钥为body,因此您可能需要将config更新为:

export default {
  heads: {
    body: {
      ...

就像现在一样,config对象包含headbody的顶级键,它们在州树的顶层没有条目。

相关问题