【问题标题】:Call function only in specific state in React with Hooks仅在 React with Hooks 中的特定状态下调用函数
【发布时间】: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


    【解决方案1】:

    您可以通过useEffect 中的条件来实现此目的。如我所见,您已经将xIsNext 作为useEffect 中的依赖项传递。所以每次xIsNext的值改变时都会调用。

    你可以做的是:设置条件

    useEffect(() => {
     if (!xIsNext) {
        handleCPUTurn();
     }     
    } ,[xIsNext]);
    

    这只会在xIsNext=false 时运行handleCPUTurn

    【讨论】:

      猜你喜欢
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      相关资源
      最近更新 更多