我是 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.todos
和state.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/