【问题标题】:ReactJS : update state regularly in a specific time intervalReactJS:在特定的时间间隔内定期更新状态
【发布时间】:2020-08-18 03:46:38
【问题描述】:

我正在创建一个传感器应用程序,我必须使用从后端接收的数据以 15 秒的时间间隔定期更新状态。尽管我可以在时间间隔内从后端成功获取数据,但我无法更新 ReactJS 中的状态。代码如下:

async regularCallAPI(){
    let result;
    const url = "http://..../...";
    await fetch(url).then( res =>  res.json()).then( res => { result = res});
    console.log("Regular Data from Backend : ", result);
    let updatedSensors = result.map( sensor => {
        return {
            floorNum: sensor.floor_no,
            roomNum: sensor.room_no,
            sensorStatus: sensor.sensor_status,
            alertStatus: sensor.alert_status,
            ownerName: sensor.owner_name,
            email: sensor.email,
            phoneNumber: sensor.phone_number,
            recordedDateAndTime: new Date(sensor.created_date).toLocaleString()
        }
    });
    await this.setState({ sensors: updatedSensors });
    console.log("sensor state updated ...");
}

并且我以 15 秒的间隔执行了上述功能;

timerId = setInterval(this.regularCallAPI, 15000);

我遇到的问题是,第一次运行成功,第二次运行时出现这个错误:

Unhandled Rejection (TypeError): this.setState is not a function

是的,该函数已经绑定到构造函数中的组件。
这种行为的原因是什么?可能的解决方案是什么?

【问题讨论】:

    标签: reactjs components state


    【解决方案1】:

    回调是在不同的上下文中进行的。您需要绑定到 this 才能在回调中访问:

    setInterval( () => this.regularCallAPI(), 15000);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多