如何在嵌套评论数组中按id查找元素并在Reducer中新增子回复?
解决方案
核心逻辑
从现有代码写法判断你使用了Redux Toolkit(开启了Immer能力,支持直接修改state生成不可变更新),只要找到目标评论的引用,直接修改其下的comments数组即可实现嵌套回复新增,页面无需刷新自动响应状态变化。
调整后的完整代码
[sendReplyRoutine.SUCCESS]: (state, action) => { state.reply = initialState.reply; // 后端返回的新回复数据 const newReply = action.payload; // 要回复的目标评论ID const targetCommentId = state.reply.replyCommentId; // 递归查找目标评论 function findById(commentList, targetId) { for (const comment of commentList) { if (comment.id === targetId) return comment; // 存在子评论则递归查找 if (comment.comments?.length) { const found = findById(comment.comments, targetId); if (found) return found; } } return null; } const targetComment = findById(state.post.comments, targetCommentId); if (targetComment) { // 目标评论无评论列表时先初始化 if (!targetComment.comments) targetComment.comments = []; // 回复插入子列表头部,和顶层新增评论逻辑对齐 targetComment.comments.unshift(newReply); } }
说明
- 优化后的递归查找逻辑避免全量打平评论数组生成中间产物,性能优于原flatMap写法
- 内置多层空值校验,避免目标评论不存在、无comments字段场景下的报错
- 不需要额外手动拷贝评论树,Immer会自动处理不可变更新逻辑
内容的提问来源于stack exchange,提问作者kiker
相关产品推荐
相关产品推荐

