【发布时间】:2020-10-21 02:23:28
【问题描述】:
我正在尝试为帖子实现喜欢和不喜欢的功能。
当用户喜欢/不喜欢帖子并向服务器发送请求时,我更改了状态,如果请求失败,我将状态更改为以前的状态。但是以前的状态更改为新状态,我不知道为什么。
export const dislikePostAction = (
postId: string,
): ThunkAction<Promise<void>, RootState, {}, AnyAction> => {
return async (dispatch: ThunkDispatch<{}, {}, AnyAction>, getState): Promise<void> => {
console.log(getState().GroupPosts.posts); // Even here is new state
const prevState = getState().GroupPosts.posts;
console.log(prevState);
const newState = prevState.map(item => {
if (item.postId === postId) {
const newPost = item;
if (newPost.currentUserLiked === UserPostLike.DISLIKE) {
newPost.likeCount = item.likeCount + 1;
newPost.currentUserLiked = UserPostLike.NO_ACTION;
} else {
newPost.likeCount = item.likeCount - 1;
newPost.currentUserLiked = UserPostLike.DISLIKE;
}
return newPost;
} else {
return item;
}
});
console.log(prevState);
dispatch(setPosts(newState));
const response = await PostsApi.dislikePost(postId);
if (!response.success) {
console.log(prevState); // prev state here is same as newState
dispatch(setPosts(prevState));
}
};
};
我正在使用redux 和redux-thunk
【问题讨论】:
-
你正在改变动作中的状态。
-
@HMR 我将
newState存储到新变量中。 -
我认为你很难理解 JavaScript 中的对象引用是什么:
newPost = item表示 newPost 和 item 都指向同一个对象,所以newPost.likeCount = item.likeCount + 1;改变了 newPost 但因为它指向同一个引用由于 item 它也会改变 item,您可以尝试const newPost = {...item};将 newPost 设置为 item 的 浅拷贝。也许this 可以提供帮助 -
@HMR 我这样做了,但我得到了他们类型的打字稿错误。我将其更改为
new Post(item),现在可以了。 tnx.
标签: javascript reactjs react-native redux redux-thunk