JavaScript中如何按路径更新嵌套数组/对象 实现React评论嵌套回复功能
问题原因
你原来的写法没有将修改后的子评论数组同步回根数组的对应层级,你修改的originalData只是逐层复制出来的独立数组,和根数组temp没有关联,最终提交的temp还是原始值,所以不会触发更新。
正确实现思路
React状态更新要求不可变修改,我们需要沿着path逐层创建对应层级的副本,找到目标评论后,修改它的comments数组,再将修改后的内容逐层回填到上层副本中,实现代码如下:
onClick={() => { // 创建根评论数组的副本 const newComments = [...props.comments]; // 用current指针跟踪当前操作的层级,初始指向根数组 let current = newComments; // 遍历path路径 for (let i = 0; i < props.path.length; i++) { const index = props.path[i]; // 到达路径最后一位,即找到了要新增回复的目标评论 if (i === props.path.length - 1) { // 创建目标评论的副本,避免直接修改原状态 const targetComment = { ...current[index] }; // 给目标评论的comments数组新增评论 targetComment.comments = [ ...targetComment.comments, { username: "Kevin", date: "now", text: "JASDFASDF", votes: 0, comments: [], } ]; // 将修改后的目标评论回填到当前层级 current[index] = targetComment; } else { // 未到最后一层,先创建当前层级评论的副本 current[index] = { ...current[index] }; // 指针移动到下一层的comments数组 current = current[index].comments; } } // 提交更新后的完整评论数组 props.setComments(newComments); }}
逻辑验证(以path=[0,1]为例)
- 初始
current指向根数组newComments - 第一次循环i=0,不是最后一层,复制索引0的Kevin评论,将
current切换为Kevin的comments数组 - 第二次循环i=1,是路径最后一位,复制索引1的James评论,给他的
comments添加新回复后回填到当前层级 - 最终
newComments就是更新完成的完整嵌套评论数组
内容的提问来源于stack exchange,提问作者John Ko
相关产品推荐
相关产品推荐

