【问题标题】:redux reducer not updating stateredux reducer 不更新状态
【发布时间】:2017-05-23 03:57:25
【问题描述】:

我是 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;

谢谢!

【问题讨论】:

标签: reactjs redux


【解决方案1】:

您似乎对combineReducers 的工作原理有些困惑。

combineReducers 实用程序旨在定义状态树对象中的字段或“切片”,并将更新这些切片的工作委托给特定函数。在您的情况下,您似乎真的只想拥有一个state.todos 切片,但您调用combineReducers() 的方式实际上是创建state.todosstate.modifyList。此外,当您使用combineReducers 时,每个切片归约器只能看到其整体状态树的一部分。换句话说,在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 和一般化简器的部分:Introduction - Core ConceptsBasics - ReducersAPI Reference - combineReducersStructuring Reducers - Using combineReducers

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 2018-08-04
    • 1970-01-01
    • 2020-10-21
    • 2021-01-08
    • 2019-07-18
    • 2018-04-29
    • 2017-08-08
    • 2017-11-27
    相关资源
    最近更新 更多