我是Redux的新手,在尝试制作基本任务清单时通读了文档。
我似乎无法让我的减速器在列表中添加一个项目。正确的动作创建者正在开除,我认为我的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;
Run Code Online (Sandbox Code Playgroud)
谢谢!
您似乎对combineReducers工作方式有些困惑。
该combineReducers实用程序旨在在状态树对象中定义字段或“切片”,还将委派这些切片的工作委托给特定功能。在您的情况下,您似乎真的只想state.todos切片,但是调用的combineReducers()方式实际上是创建state.todos和state.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});
Run Code Online (Sandbox Code Playgroud)
您可能需要通读Redux文档中讨论combineReducers和缩减程序的各个部分: 简介-核心概念,基础知识-缩减程序,API参考-combineReducers和构建缩减程序-使用combineReducers。
| 归档时间: |
|
| 查看次数: |
10705 次 |
| 最近记录: |