使用Hooks(由React和Hooks制作的岩纸剪刀游戏正确地更新分数)

问题描述 投票:1回答:2

我正在尝试练习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;
      }
    }
  };
}

这里的问题是我在组件渲染时两个分数都得到相同的更新,即使我在返回中指定了不同的对象也是如此。

我该如何克服?在这种情况下,有反应的最好方法是什么?

javascript reactjs
2个回答
1
投票

您可以尝试这样的事情吗?>

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)
  }
  }
};
}

1
投票

难怪您为两个分数获得了相同的更新,因为您设置了相同的值:getScore(player1, player2)

© www.soinside.com 2019 - 2024. All rights reserved.