首页 > 解决方案 > How to run non-blocking/background tasks in reactJS

问题描述

I am trying to make a react component that sends a GET request to my server every 3 seconds when it is mounted. But, when I create a loop after the componentDidMount() function it doesn't render my page. Is it possible to create a background task or a non-blocking UI function or anything else that could run my loop while I render my component.

Here is my code:

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;

标签: reactjsbackground-task

解决方案


推荐阅读