reactjs - redux reducer 不更新状态

标签 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;

谢谢!

最佳答案

看起来您对如何 combineReducers 有点困惑有效。

combineReducers实用程序旨在定义状态树对象中的字段或“切片”,并将更新这些切片的工作委托(delegate)给特定函数。就您而言,看起来您真的只想拥有 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 的部分。和一般 reducer :Introduction - Core Concepts , Basics - Reducers , API Reference - combineReducers ,和Structuring Reducers - Using combineReducers .

关于reactjs - redux reducer 不更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44120848/

相关文章:

html - 如何在素材 UI 芯片中显示姓名和电子邮件?

javascript - 使用 ramda sortWith 进行不区分大小写的排序

javascript - 在自定义路线之前更新商店

javascript - react ajax请求

javascript - react : What is the best way to give keys in array element

javascript - 访问对象内部的属性

javascript - 如何测试: onClick event - Jest/Enzyeme

javascript - 如何更新 Redux + React 中的嵌套对象属性?

react-native - react 导航 : Apply SafeAreaView globally with Redux

reactjs - 在react-redux应用程序中更新部分状态时整个页面闪烁并跳转到顶部