Redux的reducer没有更新状态

3

我对Redux还不熟悉,正在阅读文档,同时试图创建一个基本的待办事项清单。

我似乎无法让我的reducer将一个项添加到列表中。正确的action creator是在触发,我认为可能是我在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;

谢谢!


你能提供完整的代码吗?你在哪里分发这个动作? 我尝试复制这个问题,但是我无法做到。https://codepen.io/olivercs/pen/dWwzpj?editors=0012 - Oliver Castillo
我的代码库位于 https://github.com/AntonEmery/react-redux-todo/tree/todo-list-redux/react-app。 - Anton Emery
1个回答

6

看起来你对 combineReducers 的工作方式有些困惑。

combineReducers 工具旨在同时定义状态树对象中的字段或“片段”,并将更新这些片段的工作委托给特定函数。在你的情况下,你似乎只想要一个 state.todos 片段,但是你调用 combineReducers() 的方式实际上创建了 state.todosstate.modifyList 两个片段。此外,当使用 combineReducers 时,每个片段的 reducer 只会看到其整体状态树的一部分。换句话说,在 todos() reducer 内部,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和reducer的部分:Introduction - Core ConceptsBasics - ReducersAPI Reference - combineReducers以及Structuring Reducers - Using combineReducers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接