依次分派React Context API操作

默认情况下,react自动管理需要一起执行的调度。因此,如果将2个调度一起编写,则react将同时执行这两个调度,然后更改状态。例如,在下面的代码中,有两个调度,并且nextPlayer调度取决于第一个HOLD_SCORE调度的状态更改。但是react首先会同时执行这两个操作,然后再更改状态。

  const holdScore = () => {
    dispatch({ type: HOLD_SCORE });
    checkWinner();
    nextPlayer();
  };

  const nextPlayer = () => {
    if (state.winner < 0) dispatch({ type: NEXT_PLAYER });
  };

我希望HOLD_SCORE调度对状态进行更改,然后对nextPlayer进行更改。这是我的减速器代码:

export default function (state, { type, payload }) {
  const activePlayer = state.players.find(
    (player) => player.id === state.activePlayer
  );

  const totalPlayers = state.players.length;

  switch (type) {
    case SET_DICE:
      return { ...state, dice: payload };
    case ADD_CURRENT_SCORE:
      activePlayer.currentScore += state.dice;

      return { ...state };
    case HOLD_SCORE:
      activePlayer.totalScore += activePlayer.currentScore;
      activePlayer.currentScore = 0;

      return { ...state };
    case NEXT_PLAYER:
      const nextPlayer =
        activePlayer.id < totalPlayers - 1 ? state.activePlayer + 1 : 0;

      return { ...state, activePlayer: nextPlayer };
    case SET_WINNER:
      if (activePlayer.totalScore >= state.scoreLimit)
        return { ...state, winner: activePlayer.id };
      else return { ...state };
    default:
      return state;
  }
}
评论