React Redux - 投票计数器未更新状态?

问题描述 投票:0回答:1

完成此编码练习并难以理解 Redux 的状态变化...每次调用 RecountVotes 函数时,“RecountVotes”案例应该激活并重新渲染 Header 组件(显示总票数),但它落后一步,显示以前的收藏票而不是当前的票...

import { PostsError, PostsLoaded, RecountVotes } from '../actions/posts';

const InitialState = {
  error: null,
  pages: 0,
  posts: [],
  votes: 0,
};

export default function posts(state = InitialState, action) {
  switch (action.type) {
    case PostsError: {
      return {
        ...state,
        error: action.error,
      };
    }

    case PostsLoaded: {
      return {
        ...state,
        error: null,
        pages: action.pages,
        posts: action.posts,
      };
    }

    case RecountVotes: {
      let votes = state.posts.reduce((prev, post) => {
        return prev + post.votes;
      }, 0);

      return {...state, votes}
    };

    default:
      return state;
  }
}

我尝试将标题变成“PureComponent”,但这似乎没有多大作用,而且它让我发疯!

javascript reactjs redux
1个回答
0
投票

Redux 不是异步的,因此当您分派操作来更新状态时,状态更改不会立即发生。这就是为什么当您在分派操作后尝试访问更新后的状态时,您会得到旧状态。

可以使用 redux-thunk 来解决这个问题,可以参考他们的官方文档。我可以为您提供示例代码(您可以根据您定制)

export const recountVotes = () => (dispatch, getState) => {
  const { posts } = getState();
  let votes = posts.reduce((prev, post) => prev + post.votes, 0);
  dispatch({ type: 'RecountVotes', votes });
};

在你的Reduce中添加下面

case RecountVotes: {
  return {...state, votes: action.votes};
};

我希望这能正常工作。另外,请尝试通过编辑这篇文章来提供更多有关您在何处使用这些内容的背景信息,以便我可以更有效地帮助您

© www.soinside.com 2019 - 2024. All rights reserved.