依次分派React Context API操作

时间:2020-04-24 16:22:22

标签: javascript reactjs

默认情况下,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;
  }
}

0 个答案:

没有答案