如何在 reactJS 中运行非阻塞/后台任务

时间:2021-07-27 20:35:06

标签: reactjs background-task

我正在尝试制作一个反应组件,该组件在安装时每 3 秒向我的服务器发送一次 GET 请求。但是,当我在 componentDidMount() 函数之后创建一个循环时,它不会呈现我的页面。是否可以在渲染组件时创建后台任务或非阻塞 UI 函数或其他任何可以运行我的循环的东西。

这是我的代码:

import React, { Component } from "react";


class Sidebar extends Component{

    constructor (props){
      super(props);

      this.checkStillAlive = this.checkStillAlive.bind(this);
    }


    componentDidMount(){
      let nextCheck = 0;
      while (true){
        let currentDate = Date.now();
        if (nextCheck < currentDate){
          nextCheck = currentDate + 3000;
          this.checkStillAlive();
        }
      }
    }

    checkStillAlive (){
        fetch('http://localhost:3100/connection' ,{
          method: 'GET',
          headers: {
            'Accept': 'application/json',
          },
        })
        .then((response) => (response.status >= 200 && response.status < 400)? response.json():{})
        .then((data) => data['on']? console.log("ok"):console.log(data['on']));
    }

    render(){

        return(
            <div>
                <Test />
            </div>
        );
    }
}

export default Sidebar;

0 个答案:

没有答案
相关问题