如何为有评论的帖子构建 React 上下文

How to structure a React Context for posts that have comments

简介

正在实施 Instagram 克隆:

  1. 用户有 post 个。
  2. 帖子可以被点赞。
  3. 用户可以在 post 秒后发表评论。
  4. 帖子有一个 totalLikes 和 totalComments 字段。
  5. 评论可以点赞
  6. 用户可以回复评论。
  7. 评论有一个 totalLikes 和 totalComments(回复)字段。

到目前为止,我一直在使用当前的 PostsContext:

const initialState = {};

export function PostsProvider({ children }) {
   const [contents, dispatch] = useReducer(contentsReducer, initialState);

   const addUserPosts = (userId, posts, unshift = false, cached = true) => { ... }

   const likePost = (postOwnerId, postId) => { ... }

   const commentPost = (postOwnerId, postId, comment) => { ... }

   const getUserPosts = (userId) => { ... }

   const getUserPost = (userId, postId) => { ... } 
}

其中,我的状态数据如下所示:

{
   userId1: { 
      posts: [ 
         {
            id,
            uri,
            totalLikes,
            totalComments,
            isLiked,
            date
         },
         ...
      ]
   },
   userId2: { posts: [...] }
 }

问题

我的问题是,我应该使用另一个上下文来评论吗?我的意思是,评论的工作方式与 posts 相同,它们可以被点赞和回复……所以也许,这是不必要的。

当用户在 post 中发表评论时:

1. The post totalComments is increased.
2. If the user is replying to a comment in the post, the replied comment's totalComments is increased too.

当用户点赞评论时,它不会影响post“数据”本身,只会影响点赞评论的总点赞数字段。

所以...如果我为评论创建一个新上下文,似乎我需要使用其中的 PostsContext,以增加 post totalComments 字段。

关于如何构建我的 post 上下文的任何想法?

注意:我的问题更多是关于上下文组织而不是其他任何问题(不看实现,只看我的有状态数据的结构和拆分上下文的想法)。

需要权衡取舍。对于多个上下文,您可以选择在单个上下文中呈现组件,从而在另一个上下文更改时减少刷新(提高性能)。

但是,如果您的大部分组件都需要访问多个上下文,那么拥有一个“商店”(单个应用程序级上下文)可能会更好。如果您使用的是 selector pattern(这不仅适用于 Redux),那么选择器可以计算原本会在多个上下文中的数据。

我正在处理一个具有多个上下文的项目,并经常考虑将它们组合起来。

如果您的项目很复杂,您可能需要考虑Redux instead of contexts. It adds complexity but solves some of the issues around organization and combining different areas of the state. If you do that I highly recommend starting with Redux Toolkit减少样板文件。