在以下情况下,如何在函数simulationOn内部更新变量executeSimulation的值:

应用程序this.state.simulationOn通过外部代码更改-> ...->重新渲染React无状态组件(Robot)->用新值调用的useEffect钩子-> executeSimulation未更新为新值simulationOn

    function Robot({ simulationOn, alreadyActivated, robotCommands }) {

        useEffect(() => {
            function executeSimulation(index, givenCommmands) {
                index += 1;
                if (index > givenCommmands.length || !simulationOn) {
                    return;
                }
                setTimeout(executeSimulation.bind({}, index, givenCommmands), 1050);
            }
            if (simulationOn && !alreadyActivated) {
                executeSimulation(1, robotCommands);
            }
        }, [simulationOn, alreadyActivated, robotCommands]);

    }


在上面的示例中,即使使用更新后的值调用了useEffect(我通过console.log进行了检查),simulationOn也从未更改为false。我怀疑这是因为simulationOn的新值从未传递给函数executeSimulation的范围,但是我不知道如何在函数executeSimulation内传递新的钩子值。

WebApp是https://finitech-sdp.github.io/operations-monitor/#/
注意:在这个问题中,我省略了非必需的代码,可以在here中找到。

最佳答案

executeSimulation函数具有失效关闭模拟,On永远不会为真,这是演示失效关闭的代码:



var component = test => {
  console.log('called Component with',test);
  setTimeout(
    () => console.log('test in callback:', test),
    20
  );
}
component(true);
coponent(false)





请注意,每次渲染时都会调用Robot,但是executeSimulation从先前的渲染开始运行,而先前的渲染在其闭包中具有先前的simulationOn值(请参见上面的过时的闭包示例)

代替在simulationOn中检查executeSimulation,您应该只在executeSimulation为true且useEffect的清除函数中的clearTimeout时启动simulationOn



const Component = ({ simulation, steps, reset }) => {
  const [current, setCurrent] = React.useState(0);
  const continueRunning =
    current < steps.length - 1 && simulation;
  //if reset or steps changes then set current index to 0
  React.useEffect(() => setCurrent(0), [reset, steps]);
  React.useEffect(() => {
    let timer;
    function executeSimulation() {
      setCurrent(current => current + 1);
      //set timer for the cleanup to cancel it when simulation changes
      timer = setTimeout(executeSimulation, 1200);
    }
    if (continueRunning) {
      timer = setTimeout(executeSimulation, 1200);
    }
    return () => {
      clearTimeout(timer);
    };
  }, [continueRunning]);
  return (
    <React.Fragment>
      <h1>Step: {steps[current]}</h1>
      <h1>Simulation: {simulation ? 'on' : 'off'}</h1>
      <h1>Current index: {current}</h1>
    </React.Fragment>
  );
};
const App = () => {
  const randomArray = (length = 3, min = 1, max = 100) =>
    [...new Array(length)].map(
      () => Math.floor(Math.random() * (max - min)) + min
    );
  const [simulation, setSimulation] = React.useState(false);
  const [reset, setReset] = React.useState({});
  const [steps, setSteps] = React.useState(randomArray());
  return (
    <div>
      <button onClick={() => setSimulation(s => !s)}>
        {simulation ? 'Pause' : 'Start'} simulation
      </button>
      <button onClick={() => setReset({})}>reset</button>
      <button onClick={() => setSteps(randomArray())}>
        new steps
      </button>
      <Component
        simulation={simulation}
        reset={reset}
        steps={steps}
      />
      <div>Steps: {JSON.stringify(steps)}</div>
    </div>
  );
};
ReactDOM.render(<App />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

10-08 00:22