【发布时间】:2021-04-30 06:09:15
【问题描述】:
我是使用 React Hooks 的新手,想知道是否可以让 useEffect() 仅针对特定的状态值触发。基本上我有一个简单的井字游戏,我希望在人类玩家轮到他们之后调用我必须处理 CPU 轮到的函数,换句话说,在 handleClick() 完成新的渲染之后基本上调用 handleCPUTurn()。
从我已经尝试过的情况来看,我可以将 handleCPUTurn 设置为一次,或者无限次直到游戏结束。下面是我处理转弯的代码。
const Game = () => {
const [history, setHistory] = useState([Array(9).fill(null)]);
const [stepNumber, setStepNumber] = useState(0);
const [xIsNext, setXIsNext] = useState(true);
const handleCPUTurn = () => {
const pointInHistory = history.slice(0, stepNumber + 1);
const current = pointInHistory[stepNumber];
const squares = [...current];
let randomSqaure = Math.floor(Math.random() * 8);
if (calculateWinner(squares)) return;
while(true){
if (squares[randomSqaure]) {
randomSqaure = Math.floor(Math.random() * 8);
continue;
}
else {
squares[randomSqaure] = 'O';
setHistory([...pointInHistory, squares]);
setStepNumber(pointInHistory.length);
setXIsNext(xIsNext);
break;
}
}
}
const handleClick = (i) => {
const pointInHistory = history.slice(0, stepNumber + 1);
const current = pointInHistory[stepNumber];
const squares = [...current];
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = 'X';
setHistory([...pointInHistory, squares]);
setStepNumber(pointInHistory.length);
setXIsNext(!xIsNext);
}
useEffect(() => (
handleCPUTurn(),[xIsNext]));
【问题讨论】:
标签: reactjs react-hooks