使用 React 有条件地停止游戏循环

Stop game loop on conditional with React

我无法在有条件的情况下停止循环。单击按钮后我可以停止间隔,但在循环增量等条件后无法停止间隔。这个简单的例子试图在 5 次循环后停止间隔循环。

任何解决方案将不胜感激!

import React, { useState } from 'react';

let gameLoop: any;

function App() {
  const [loopCount, setLoopCount] = useState(0);
  const [running, setRunning] = useState(true);

  const gameLogic = () => {
    console.log('Game logic!')
  }

  const loop = () => {
    gameLogic();
    setLoopCount(prev => {
      const newCount = prev + 1;
      console.log(newCount)
      return newCount
    });

    // Stop the loop on a conditional
    if(loopCount >= 5){
      clearInterval(gameLoop)
    }
  }

  const handleStartButtonClick = () => {
    gameLoop = setInterval(loop, 1000)
    setRunning(true);
  }

  const handleStopButtonClick = () => {
    clearInterval(gameLoop);
    setRunning(false);
  }

  const handleResetButtonClick = () => {
    setLoopCount(0);
    console.clear();
  }

  return (
    <div className="App">
      <div>
        <button onClick={handleStartButtonClick}>Start</button>
        <button onClick={handleStopButtonClick}>Stop</button>
        <button onClick={handleResetButtonClick}>Reset</button>
      </div>
    </div>
  );
}

export default App;

解决方案是将条件放在组件级别,而不是循环方法中。

import React, { useState } from 'react';

let gameLoop: any;

function App() {
  const [loopCount, setLoopCount] = useState(0);
  const [running, setRunning] = useState(true);

  const gameLogic = () => {
    console.log('Game logic!')
  }

  const loop = () => {
    gameLogic();
    setLoopCount(prev => {
      const newCount = prev + 1;
      console.log(newCount)
      return newCount
    });


  }
    //MOVE OUTSIDE GAME LOOP
    // Stop the loop on a conditional
    if(loopCount >= 5){
      clearInterval(gameLoop)
    }

  const handleStartButtonClick = () => {
    gameLoop = setInterval(loop, 1000)
    setRunning(true);
  }

  const handleStopButtonClick = () => {
    clearInterval(gameLoop);
    setRunning(false);
  }

  const handleResetButtonClick = () => {
    setLoopCount(0);
    console.clear();
  }

  return (
    <div className="App">
      <div>
        <button onClick={handleStartButtonClick}>Start</button>
        <button onClick={handleStopButtonClick}>Stop</button>
        <button onClick={handleResetButtonClick}>Reset</button>
      </div>
    </div>
  );
}

export default App;