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

问题描述 投票:1回答:1

我正在建立一个react应用程序,用于在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秒取一次数据,并在不刷新网页的情况下更新表格。谁能帮我解决这个问题?

javascript reactjs restapi
1个回答
0
投票

根据我的要求,因为我需要在40秒的时间间隔内加载表格数据,我可以使用Javascript内置的方法。(1)、(2)、(3)、(4)、(5)、(6)、(7)、(8)。 里面 componentWillMount() 方法.如题中所示初始数据加载后刚开始的 效果图() 可从 componentDidMount().

下面是我在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);
   }

0
投票

据我所知,我认为不可能在不重新渲染组件(不突变状态)的情况下更新状态,因为react使用的是浅层渲染,它基本上是检查之前和当前的状态,如果它们不匹配就重新渲染,如果你问我,要做到这一点,没有内存泄漏和一堆bug,你可以这样做。

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

 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) 突变状态。这不是一个好主意 (这将导致更多的错误和错误)

© www.soinside.com 2019 - 2024. All rights reserved.