为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕码人2483693 2022-06-09 09:58:32
我正在尝试在练习 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 时对两个分数进行相同的更新。我该如何克服呢?在那些有反应的情况下,哪种方法最好?
查看完整描述

2 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

你能试试这样的吗


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)

  }

  }

};

}


查看完整回答
反对 回复 2022-06-09
?
忽然笑

TA贡献1806条经验 获得超5个赞

难怪您会为两个分数获得相同的更新,因为您设置了相同的值: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)

  }

});


查看完整回答
反对 回复 2022-06-09
  • 2 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号