Javascript 如何在reducer中推入嵌套数组
上图显示了我试图发送回复操作时发生的情况 当前正在尝试将输入字段值等推送到replyComments…但即使在分派此操作时,它仍然为空。。。。减速器首先检查主索引,然后检查最小索引,然后将其推入replyComments。有人知道我怎么解决这个问题吗Javascript 如何在reducer中推入嵌套数组,javascript,reactjs,reducers,Javascript,Reactjs,Reducers,上图显示了我试图发送回复操作时发生的情况 当前正在尝试将输入字段值等推送到replyComments…但即使在分派此操作时,它仍然为空。。。。减速器首先检查主索引,然后检查最小索引,然后将其推入replyComments。有人知道我怎么解决这个问题吗 case types.REPLY\u注释:{ 返回{ ……国家, enableToggleComment:true, imageData:state.imageData.map(image=>image.id==action.majorInde
case types.REPLY\u注释:{
返回{
……国家,
enableToggleComment:true,
imageData:state.imageData.map(image=>image.id==action.majorIndex?
{
…图像,
评论:{
[action.minorIndex]:{
replyComments:[…image.comments.replyComments,{comment:action.newComment,likeComment:image.toggle,enableReply:false}]
}
}
}:图像
)
}
}
编辑:
我知道,我注意到这是由于缺少[action.minorIndex]
的一个键,当使用?
操作符并想要返回一个对象时,你应该添加括号,否则你就是在声明一个范围(就像我做的那样)
我只添加了
action.replyText
,但您现在应该可以添加其余内容了
case types.REPLY\u注释:{
返回{
……国家,
enableToggleComment:true,
imageData:state.imageData.map(图像=>
image.id==action.generalIndex
? {
…图像,
注释:image.comments.map((注释,i)=>
i==action.majorIndex
? {
……评论,
答复:[
…comment.replyComments,
action.replyText
]
}
:评论
)
}
:图像
)
};
}
当前正在尝试将输入字段值等推送到replyComments…但没有任何成功
。。。。没有任何成功是没有帮助的。这是暗示,因为你确实是张贴在如此。您的实际错误或异常消息是什么?此外,我没有看到任何与“推送”相关的代码。您所显示的只是一个数据结构。我想将其放入replyComments数组中…您需要查看的唯一内容是…image.comments.replyComments…这是尚未工作的部分…是image.id==action.majorIndex
evertrue
?是否确实要比较相同的数据类型(数字与数字、字符串与字符串等)?尝试在return
语句之前在变量中构建结构,以便控制台。记录值并查看发生的情况。在图中,comments
是一个数组,但在代码中,您将其视为一个对象comments:{..}
,并且由于在图像comments
中仍然是一个数组,image.id==action.majorIndex
条件可能从未true
(该属性的值从未更改为对象
)。当我这样做时,它会显示“replyComments未定义”。我已编辑我的回复。我的答案完全不同。现在应该可以了
case types.REPLY_COMMENT: {
return {
...state,
enableToggleComment: true,
imageData: state.imageData.map(image => image.id === action.majorIndex ?
({
...image,
comments: {
[action.minorIndex]: {
replyComments: [...image.comments[action.minorIndex].replyComments, { comment: action.newComment, likeComment: image.toggle, enableReply: false }],
}
}
}) : image
)
}
}