我怎样才能在react redux-toolkit中实现这个目标?

发布于 2025-01-10 18:56:56 字数 859 浏览 0 评论 0原文

所以,我有映射在页面中的 posts 数组。当我单击每个帖子时,它将以模式打开。

帖子有一个“喜欢”按钮,因此,我希望当用户在模式中打开帖子时喜欢该帖子,它会自动更新所有帖子都映射到的提要中的帖子喜欢状态。

场景

现在,当我喜欢该帖子时,我会在有效负载中收到以下响应:

{
   id: "620ca78f3b36d45714ca4c1e"
   postId: "6dks2b92bjd99sndkd9j3",
   liked: true
   msg: "You liked the post."
   success: true
}

现在的问题是如何从帖子数组中更新喜欢数组。

单柱结构

{
   _id,
   ...other,
   likes: [],
}
const updatedPost = (find that specific post from the array using the postId I recieved and update its likes array)
return {
        ...state,
        loading: false,
        error: null,
        post: [...state.posts, updatedPost],
        data: payload,
      };

So, I have the posts array that is mapping in a page. when I clicked on each post it will open in modal.

Posts have a like button so, I want when user Like the post while it's open in modal it will automatically update that post liked status in that feed where all posts are mapped over.

Scenario

Now, when I like the post I receive the following response in the payload:

{
   id: "620ca78f3b36d45714ca4c1e"
   postId: "6dks2b92bjd99sndkd9j3",
   liked: true
   msg: "You liked the post."
   success: true
}

Now the question is how do I update the likes array from the post array.

Single Post Structure

{
   _id,
   ...other,
   likes: [],
}
const updatedPost = (find that specific post from the array using the postId I recieved and update its likes array)
return {
        ...state,
        loading: false,
        error: null,
        post: [...state.posts, updatedPost],
        data: payload,
      };

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我很OK 2025-01-17 18:56:56

首先,您必须通过 id 或您正在使用的任何唯一实体查找特定帖子的索引。然后通过向其分配新的帖子详细信息来更改该索引处的帖子数组。

const postIndex = state.posts.findIndex((p)=>p.id===payload.id);
let posts=[...state.posts];
if(postIndex!=-1){
    posts[postIndex]=updatedPost; // updatedPost Object whatever you want to change
    // for appending likes i.e.,
    // posts[postIndex].likes.push('id') // sample
  
}
state.loading=false; // use this scheme for updating state
state.error=null;
state.posts=posts;
state.data=payload;

First you have to find index of the specific post by id or whatever unique entity you are using. And then change posts array at that index by assigning new post details to it.

const postIndex = state.posts.findIndex((p)=>p.id===payload.id);
let posts=[...state.posts];
if(postIndex!=-1){
    posts[postIndex]=updatedPost; // updatedPost Object whatever you want to change
    // for appending likes i.e.,
    // posts[postIndex].likes.push('id') // sample
  
}
state.loading=false; // use this scheme for updating state
state.error=null;
state.posts=posts;
state.data=payload;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文