反应钩子.定期运行使用效果 [英] React hooks. Periodic run useEffect

查看:44
本文介绍了反应钩子.定期运行使用效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定期获取数据并将其更新到屏幕上.我有这个代码:

I need periodically fetch data and update it to the screen. I have this code:

const [temperature, setTemperature] = useState();

useEffect(() => {

fetch("urlToWeatherData")
  .then(function(response) {
     if (response.status !== 200) {
      console.log(
        "Looks like there was a problem. Status Code: " + response.status
      );
      return;
    response.json().then(function(data) {
     console.log(data[0].temperature);
     setTemperature(data[0].temperature);

    });
  })
  .catch(function(err) {
    console.log("Fetch Error :-S", err);
  });
 }, []  );

那么,例如,有没有什么巧妙的方法可以每 15 秒运行一次?谢谢!

So, is there any neat way to run it every 15 seconds, in example? Thanks!

推荐答案

把它包裹在一个区间内,不要忘记返回一个teardown函数,在组件卸载的时候取消这个区间:

Wrap it in an interval, and don't forget to return a teardown function to cancel the interval when the component unmounts:

useEffect(() => {
  const id = setInterval(() => 
    fetch("urlToWeatherData")
      .then(function(response) {
         if (response.status !== 200) {
          console.log(
            "Looks like there was a problem. Status Code: " + response.status
          );
          return;
        response.json().then(function(data) {
         console.log(data[0].temperature);
         setTemperature(data[0].temperature);
        });
      })
      .catch(function(err) {
        console.log("Fetch Error :-S", err);
      });
  ), 15000);

  return () => clearInterval(id);  
}, []);

这篇关于反应钩子.定期运行使用效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆