React Native - 递归 setTimeout 重复 运行 一些东西

React Native - recursive setTimeout to repeatedly run something

下面的代码只是在加载数据时出现错误(特别是临时网络丢失)时出现的屏幕模型。我想做的是在 运行 上挂载 'refresh' 函数并保持 运行 每 10 秒更新一次,直到变量 'online' 从 'false' 变为'true'。这里我用一个按钮来改变它,在真实的屏幕中它将是一个加载数据的异步调用(如果数据加载,它将变为 true)。所以想法是不断尝试加载数据。

下面代码中发生的事情是控制台每 10 秒记录一次 'still offline',但是当我按下按钮时,它正确地记录了 'back on line' 但随后又返回到记录 'still offline' 每10秒。它应该清除超时,实际上屏幕将被卸载。

 const [online, setOnline] = useState(false);
  const [loading, setLoading] = useState(false);
      
  const handleChange = () => {
    setOnline(!online);
  };

  const refresh = useCallback(async () => {
    setLoading(true);
    
    // in the real screen the following will be assigned to 'online'
    // const online = await loadData()
   
    if (!online) {
      setLoading(true);
      setTimeout(refresh, 10000);
      console.log('still offline');
    } else {
      setLoading(false);
      clearTimeout(refresh);
      console.log('back on line');
    }
  }, [online]);

  useEffect(() => {
    setTimeout(refresh, 10000);
  }, [online, refresh]);

  return (
    <View>
      {online ? <Text>Online</Text> : <Text>Offline</Text>}
      {loading ? <Text>Loading</Text> : <Text>IDLE</Text>}
      <Button title="Go Online" onPress={handleChange} />
    </View>
  );

如果您想取消之前设置的定时器,您需要存储 setTimeout 返回的定时器 ID,您不能传递 setTimeout 回调函数本身。

const myTimerID = setTimeout(refresh, 10000);
...
clearTimeout(myTimerID)

看看我的sample