我正在尝试更新状态内对象数组内的特定值(在本例中为列表内的注释)。在本例中,注释位于 msgs 键内。
const list = [{
id: 1,
text: "list text",
msgs: [{
id: 1,
comment: "comment",
commentID: "ab37afa-c17-e4f-f103-4715b72f14ec"
}]
},
{
id: 2,
text: "list text 2",
msgs: [{
id: 2,
comment: "comment2", <--- trying to update this value
commentID: "ab37afa-c17-e4f-f103-4715b72f14ec-2"
},
{
id: 2,
comment: "comment3",
commentID: "ab37afa-c11323127-e4f-f103-4715b72f14ec-2"
}]
}
];
我目前正在尝试使用 reducer :
case "EDIT_COMMENT":
temp = state.filter((list => list.id === parseInt(action.comment.id))) //getting the list that I want
const msgs = [].concat(...temp).map(x=> ({
id: x.id,
comment : x.comment,
commentID : x.commentID
})) // trying to get the messages inside the state
// I honestly don't know what to put here
return msgs.map( msg => {
if(msg.commentID === action.payload.commentID){
return {...}
}
}
)
我无法得到答案/解决方案来更新我想要的 reducer 数据,如果有人可以帮助我解决这个问题,我将不胜感激。 预先感谢,祝周末愉快:)
最佳答案
如果我理解正确,您想要更新 state
任何给定项目上的任何嵌套 msg
注释(我假设它与所示列表的形式匹配)在你的问题中) - 在这种情况下,一个简单的解决方案可能如下:
case "EDIT_COMMENT": {
return state.map(messageItem => {
return {
// Clone input messageItem
...messageItem,
// Overwrite msgs field with new msgs array
msgs : messageItem.msgs.map(commentItem => {
if(commentItem.commentID === action.payload.commentID) {
return {
// Clone input commentItem
...commentItem,
// Overwrite fields that this action should update,
// on commentItem matching by comment id ie, "comment"
// from action payload
comment : action.payload.comment
}
}
else {
// If message does not match actions comment id, return
// a clone of commentItem to mapped list
return {...commentItem}
}
})
}
});
}
这里的假设是:
state
是一个与问题中所示的list
形式匹配的数组- 操作负载中的
commentId
对于msg
子数组中的评论来说是唯一的。 - 操作负载中的
comment
字段包含新的评论字符串,用于更新现有的匹配评论
希望有帮助!
关于javascript - 使用 reducer 更新状态内的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59330350/