猿问

使用 Hooks 正确更新分数(使用 React 和 Hooks 制作的剪刀石头布游戏)

我正在尝试在练习 Hooks 时实现一个简单的计数器:


function App() {

  const cpuWeapon = ["paper", "rock", "scissor"];

  const [playerChoice, setPlayerChoice] = useState({

    playerOne: {

      choice: "",

      score: 0

    },

    playerTwo: {

      choice: "",

      score: 0

    }

  });


  const { playerOne, playerTwo } = playerChoice;


  const selectWeapon = weapon => {

    const player1 = weapon;

    const player2 = cpuWeapon[Math.floor(Math.random() * 3)];


    setPlayerChoice({

      playerOne: {

        choice: player1,

        score: getScore(player1, player2)

      },


      playerTwo: {

        choice: player2,

        score: getScore(player1, player2)

      }

    });

  };


  const getScore = (pl1, pl2) => {

    if (pl1 === "paper") {

      if (pl2 === "scissor") {

        return playerTwo.score + 1;

      } else if (pl2 === "rock") {

        return playerOne.score + 1;

      }

    }

  };

}

这里的问题是,即使我在返回时指定了不同的对象,我也会 在组件 render 时对两个分数进行相同的更新。


我该如何克服呢?

在那些有反应的情况下,哪种方法最好?


慕码人2483693
浏览 95回答 2
2回答

慕村225694

你能试试这样的吗function App() {const cpuWeapon = ["paper", "rock", "scissor"];const [playerOne,setPlayerOne]=useState(0)const [playerTwo,setPlayerTwo]=useState(0)const { playerOne, playerTwo } = playerChoice;const selectWeapon = weapon => {const player1 = weapon;const player2 = cpuWeapon[Math.floor(Math.random() * 3)];getScore(player1, player2)};const getScore = (pl1, pl2) => {if (pl1 === "paper") {  if (pl2 === "scissor") {    setPlayerTwo(playerTwo+1)  } else if (pl2 === "rock") {     setPlayerOne(playerOne+1)  }  }};}

忽然笑

难怪您会为两个分数获得相同的更新,因为您设置了相同的值:getScore(player1, player2)我建议您将getScore功能替换为:const getWinner = (pl1, pl2) => {  // Compare pl1 and pl2 and return:  // * 0 in case of tie,  // * 1 if player one wins,  // * 2 if player two wins};然后,在您的selectWeapon函数中,添加:...const winner = getWinner(player1, player2);setPlayerChoice({  playerOne: {    choice: player1,    score: playerOne.score + (winner === 1 ? 1 : 0)  },  playerTwo: {    choice: player2,    score: playerTwo.score + (winner === 2 ? 1 : 0)  }});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答