反应-更新处于未知深度的redux状态的嵌套对象

时间:2020-05-24 15:27:40

标签: javascript reactjs redux

当用户加载博客帖子页面时,将提取帖子并将其评论和子注释以以下结构存储在Redux状态:

forumPost: {
             id: #,
             data: {object},
             comments: [
               {
                 id: #,
                 data: {object},
                 comments: [
                   {
                     id: #,
                     data: {object},
                     comments: [...]
                   },
                   ...
                 ]
               },{
                 id: #,
                 data: {object},
                 comments: [...]
               },
              ...
           }

当用户发布新评论/子评论时,它会发布到数据库中并在本地添加到Redux状态。我在第二部分遇到问题

我创建了一个函数,用于查找要发布的评论的父评论的路径,但是在将新评论注入当前状态时遇到困难。

const findPath = (comments, parentId) => {
  let path = [];

  const findIndex = (arry, count) => {
    for (; count < arry.length; count++) {
      if (arry[count].id === parentId) {
        path = "forumPost.comments[" + count + "].comments";
        return true;
      }
      if (arry[count].comments && arry[count].comments.length > 0) {
        if (findIndex(arry[count].comments, 0)) {
          path = path
            .split("forumPost")
            .join("forumPost.comments[" + count + "]");
          return true;
        }
      }
    }
  };

  findIndex(comments, 0);
  return path;             //Returns the parent's path as 'forumPost.comments[a].comments[b].comments'
};

我可以创建一个全新的状态,添加新的注释,并替换旧的状态,但是这样做很昂贵,并且(据我所知)使组件无法判断Redux状态(映射到props) )已更改。

因此,做完一些研究后,我了解到redux对更新和替换状态的处理方式有所不同,而我想做的就是更新状态。

我尝试使用.update(),…,传播和dot-prop,但是无法使其正常工作(很可能是因为我使用它们的方式不正确)……这就是为什么我在这里。您如何使用新的注释对象将状态更新为深度未知的注释数组之一?

此外,我现在知道,最佳实践是使Redux状态保持尽可能浅。但是目前的结构就是它。

0 个答案:

没有答案