繁体   English   中英

在 React 生命周期方法中设置获取数据的时间间隔

[英]Set Time Interval for Fetching Data inside React Life Cycle Methods

我正在构建一个反应应用程序,用于在 rest-api 中显示数据。为了做到这一点,我使用了 componentDidMount 方法并成功获取数据而没有任何混淆。 我的代码片段如下所示。

  componentDidMount() {
        fetch('http://localhost:5000/sensors')
          .then(res => res.json())
          .then(json => {
            this.setState({
              isLoaded: true,
              sensors: json,
            })
            console.log(this.state.sensors);
          });

  }

我的要求是每 40 秒获取一次数据并更新表而不刷新 web 页面。 谁能帮我解决这个问题?

根据我的要求,因为我需要以 40 秒的时间间隔加载表数据,我可以在componentWillMount()方法中使用 Javascript 内置方法setInterval() 如问题所示,可以从componentDidMount()完成render()之后的初始数据加载。

下面是我以 40 秒的时间间隔获取数据的代码。

 componentWillMount(){
     setInterval(() => {
      fetch('http://localhost:5000/sensors')
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          sensors: json,
        })
        console.log(this.state.sensors);
      });
     }, 40000);
   }

据我所知,我认为如果不重新渲染组件(没有变异状态)就不可能更新 state,因为 react 使用浅渲染,它基本上检查以前和当前的 state,如果它们不匹配,则重新渲染,如果你问我,在没有 memory 泄漏和一堆错误的情况下做到这一点,你可以

a)使用单独的组件来获取目的并显示结果(如您所说的表格),以便只有组件重新渲染(并使用 redux 或 contextAPI。无论您想要什么),您也可以在用户渲染时使用 componentWillUnmount (将被弃用)另一个页面来清除间隔。 (或者您可以使用钩子并返回 function 以清除间隔)

 useEffect(()=>{
     const interval = setInterval(()=>{
         //fetch here
     },40000);
     return () => {
         cleanInterval(interval)
     }
 },[tableData /*this is supposed to be the state value of the data you fetch*/])

b) 突变 state。 不是一个好主意(它会导致更多的错误和错误)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM