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 时停止递归。有没有其他方法可以实现这段代码,我只想在状态值为真时重复执行一个函数。谢谢