【发布时间】:2016-10-26 10:49:44
【问题描述】:
所以在我的减速器中,我有一个名为“todos”的对象数组,而“todos”的一个对象有一个状态,它也是一个名为“cmets”的对象数组。在每个“cmets”数组中,我想定义一个字符串状态“commentText”,但我似乎不知道该怎么做。任何帮助将不胜感激。
以下是我想要实现的示例:
let todoReducer = function(todos = [], action){
switch(action.type){
case 'ADD_TODO':
return [{
comments:[{
commentText: action.commentText
}]
}, ...todos]
case 'CREATE_COMMENT_ARRAY':
return [{
commentText: action.eventValue
], ...todos.comments] //Referencing todos.comments as 'comments' array of objects of an object of 'todos' array. Would like to directly update if possible and build up 'comments' array.
default:
return todos
}
}
export default todoReducer
新编辑**:
case 'UPDATE_COMMENT':
return todos.map(function(todo){
if(todo.id === action.id){
//want to add a new a 'comment' object to the todo's 'comments' array
//Something like the following:
todo.comments: [{
commentText: action.commentText
}, ...todo.comments]
}
})
【问题讨论】:
-
Updeep 可以轻松执行嵌套对象和数组的更新;我建议看看它。
-
@xiaofan2406 我检查了它,但我似乎无法很好地掌握这个概念。如果你不可以根据我提供的内容提供一个例子吗?谢谢
-
您是否尝试更新特定 Todo 的
commentText?如果是这样,您可能需要为 Todos 提供唯一 ID,以便您可以过滤它们的列表以找到您需要更新的 ID。否则就无法区分一个 Todo 和另一个。 -
@dannyid 是的,就是这样!如果你不介意,你能举个例子吗?我似乎无法让它工作......
标签: javascript reactjs redux react-jsx react-redux