簡體   English   中英

當 redux 中的 state 更改時,存儲在變量中的先前 state 也會更改

[英]Previous state stored in variable changes too when state change in redux

我正在嘗試為帖子實現喜歡和不喜歡的功能。

當用戶喜歡/不喜歡帖子並向服務器發送請求時,我更改了 state,如果請求失敗,我將 state 更改為以前的 state。 但是以前的 state 更改為新的 state ,我不知道為什么。

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));
        }
    };
};

我正在使用reduxredux-thunk

我用new Post(item)創建了新的Post object 並解決了問題。

const newPost = new Post(item)

因為您將newState分配給prevState而不是對其進行變異,所以它將引用prevState中 prevState 的地址,並且它將更改prevState而您應該通過像這樣變異prevState創建一個新的 Obj 或數組:如果數組:

   const prevState =[... getState().GroupPosts.posts];

如果 Object:

 const prevState ={... getState().GroupPosts.posts};

或者您可以使用Object.assign()將創建一個新的 Object 而不是參考 memory 中的prevState地址。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM