小编Suj*_*jit的帖子

setTimeout() 函数未检测到状态更改并继续执行递归函数

useEffect(() => {
  playLoop();
}, [state.playStatus]);

const playLoop = () => {
  if (state.playStatus) {
    setTimeout(() => {
      console.log("Playing");
      playLoop();
    }, 2000);
  } else {
    console.log("Stopped");
    return;
  }
};

Output: 
Stopped
// State Changed to true
Playing
Playing
Playing
Playing
// State Changed to false
Stopped
Playing // This is the problem, even the state is false this still goes on execute the Truthy stalemate
Playing
Playing
Run Code Online (Sandbox Code Playgroud)

我正在研究 react-native,我希望在状态值变为 false 时停止递归。有没有其他方法可以实现这段代码,我只想在状态值为真时重复执行一个函数。谢谢

javascript reactjs react-native

5
推荐指数
1
解决办法
564
查看次数

标签 统计

javascript ×1

react-native ×1

reactjs ×1