redux 异步形实转换程序未更新状态

x759pob2  于 2023-10-19  发布在  其他
关注(0)|答案(2)|浏览(97)

我试图更新我的redux状态的一个元素,但我无法使其工作。我省略了一些我认为不必要的部分

我的postSlice是

const INITIAL_STATE = {
  posts: [],
  error: '',
};

...

 builder.addCase(commentPostAsync.fulfilled, (state, action) => {
      const updatedPost = action.payload;
      state = {
        ...state,
        posts: state.posts.map((post) => {
          // console.log(post._id);
          return post._id === updatedPost._id ? { ...post, updatedPost } : post;
        }),
      };
 });

后端工作正常,因为如果我刷新页面,新的评论会如预期的那样出现在帖子中。
Action.payload在后端使用新的注解和map函数中的条件更新了post数据,因为如果我将日志移动到条件中,只会记录正确的post_id。
所以问题是{... post,updatedPost }没有更新状态,我不知道为什么。

我的Feed.jsx组件

const Feed = () => {
  const { user } = useSelector((state) => state.auth.user);
  const { posts } = useSelector((state) => state.post);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getTimeLineAsync(user._id));
  }, [dispatch]);

  return (
    <StyledFeed className='feed'>
      <div className='feed__container'>
        <Share />
        {posts &&
          posts?.map((post) => {
            return <Post post={post} key={post._id} />;
          })}
      </div>
    </StyledFeed>
  );
};

export default Feed;

我的Post.jsx组件

{isOpenComments && (
          <div className='comments__container'>
            <div className='old-comments__container'>
              {post &&
                post.comments.map((comment) => {
                  return <Comment comment={comment} key={comment._id} />;
                })}
            </div>
            <div className='add-comments__container'>
              <div className='add-comments__avatar'>
                {user && <img className='user__avatar' src={user.avatar} alt='' />}
              </div>
              <form className='add-comments__input'>
                <input
                  className='input'
                  type='text'
                  placeholder='Write a comment...'
                  onChange={handleInputChange}
                  name='text'
                />
                <button className='icon' type='submit' onClick={sendComment}>
                  <SendIcon />
                </button>
              </form>
            </div>
          </div>
        )}

UPDATE这是console.log(updatedPost)的结果

{
comments: (18) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
createdAt: "2021-11-25T19:24:40.196Z"
description: "test last "
image: "https://travelprnews.com/wp-content/uploads/2021/11/https___specials-images.forbesimg.com_imageserve_920377840_0x0.jpg"
likes: []
totalComments: 21
updatedAt: "2021-11-27T08:42:17.264Z"
userId: "619a1cc54ac9c7217520e150"
__v: 0
_id: "619fe2f80481f8a4edd791f4"
}

如果需要更多信息,请让我知道。希望有人能告诉我代码出了什么问题。
Thanks in advance

更新已解决

我在这个post中找到了解决方案

builder.addCase(commentPostAsync.fulfilled, (state, action) => {
      const updatedPost = action.payload;
        const index = state.posts.findIndex((post) => post._id === action.payload._id);

        const newArray = [...state.posts];

        newArray[index] = updatedPost;

        return {
          ...state,
          posts: newArray,
        };
xdnvmnnf

xdnvmnnf1#

这里的问题是,你错过了解构updatedPost。将构建器的大小写更改为以下应该会按预期更新状态(假设action.payload有post对象):

builder.addCase(commentPostAsync.fulfilled, (state, action) => {
      const updatedPost = action.payload;
      state = {
        ...state,
        posts: state.posts.map((post) => {
          // console.log(post._id);
          return post._id === updatedPost._id ? { ...post, ...updatedPost } : post;
        }),
      };
    });
9vw9lbht

9vw9lbht2#

内部状态更新不起作用。试试下面的例子

const INITIAL_STATE = {
    posts: [],
    error: '',
  };
  
  
  
   builder.addCase(commentPostAsync.fulfilled, (state, action) => {
        const updatedPost = action.payload;
        const posts = state.posts.map(post => {
          if(post._id === updatedPost._id) {
            Object.assign(post, updatedPost)
          }
          return post
        })
        state.posts = posts
   });

相关问题