亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 87 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號