redux 状态在元素刷新或重新渲染之前不会更新

时间:2021-01-11 16:30:33

标签: reactjs react-redux react-state

我有两个组件 - 第一个是从数据库中获取帖子的提要,第二个是所选帖子的弹出窗口。在他们两个上,我都有喜欢和评论的数量。我正在使用 redux 进行状态管理,并且我制作了两个减速器 LIKE_POST 和 UNLIKE_POST,它们工作得很好(每当我喜欢或不喜欢弹出窗口中的帖子时,帖子和帖子中的状态都会更新以及提要和弹出窗口-重新渲染到正确的点赞数)。

        case LIKE_POST:
        case UNLIKE_POST:
            let index = state.posts.findIndex((post) => post.postId === action.payload.postId);
            state.posts[index] = action.payload;
            if (state.post.postId === action.payload.postId) {
                let comments = state.post.comments;
                state.post = action.payload;
                state.post.comments = comments;
            }
            return {
                ...state,
            }

但是,我找不到让我的 SUBMIT_COMMENT 减速器按预期工作的方法。我想让它每当我发表评论时,评论数量都会在弹出窗口和提要上重新呈现。我发现只有在我刷新窗口或重新渲染某个元素后状态才会改变(例如,如果我在弹出窗口上发表评论,它会显示正确的数字,但在我刷新之前不会在提要中显示它)。

case SUBMIT_COMMENT:
            let commentCount = state.post.commentCount;
            return {
                ...state,
                post: {
                    ...state.post,
                    comments: [action.payload, ...state.post.comments],
                    commentCount: commentCount +1
                }
            }

0 个答案:

没有答案