redux reducer不更新状态

时间:2017-05-22 19:37:27

标签: reactjs redux

我是Redux的新手,在我尝试制作基本待办事项列表的同时阅读文档。

我似乎无法让我的reducer将一个项目添加到列表中。正确的行动创造者正在解雇,我想我的Object.assign陈述中可能有一些我不理解的东西。以下是我的store.js文件。

const defaultState = {
    todos:[
  {
    text: 'walk gilbert'
  },
  {
    text: 'cook dinner'
  },
  {
    text: 'clean bathroom'
  }
 ]
}

function todos(state = defaultState) {
  return state;
}

function modifyList(state = defaultState, action) {
  switch(action.type) {
    case 'ADD_TODO':
    return Object.assign({}, state, {
        todos: [
          ...state.todos,
        {
            text: action.text,
        }
      ]
    })

  default:
    return state;
 }
}

const rootReducer = combineReducers({todos, modifyList})

const store = createStore(rootReducer, defaultState);

export default store;

谢谢!

1 个答案:

答案 0 :(得分:4)

您似乎对combineReducers的工作方式感到有些困惑。

combineReducers实用程序旨在定义字段或"切片"在您的状态树对象中,并将更新这些切片的工作委托给特定的功能。在您的情况下,看起来您真的只想拥有state.todos切片,但您拨打combineReducers()的方式实际上是创建state.todosstate.modifyList。此外,当您使用combineReducers时,每个切片缩减器只能看到整个状态树的一部分。换句话说,在todos()缩减器内部,state参数只是 todos部分。

所以,你想要的是更像这样的东西:

const defaultTodosState = [
    {text : 'walk gilbert'},
    {text : "cook dinner"},
    {text : "clean bathroom"}
];

function todos(state = defaultTodosState, action) {
  switch(action.type) {
    case 'ADD_TODO': {
        return [
          ...state,
          {text: action.text}
        ]
    }
    default:
      return state;
   }
}

const rootReducer = combineReducers({todos});

您可能需要仔细阅读Redux文档中讨论combineReducers和缩减器的部分:Introduction - Core ConceptsBasics - ReducersAPI Reference - combineReducers和{{3} }。

相关问题