微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我正在尝试制作一个反应组件,该组件在安装时每 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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。