reactjs - 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;
解决方案
推荐阅读
- java - 如何在java中的一行中将APIException消息包装在数组中
- c++ - C ++我如何覆盖类中的 << 运算符
- python - 如何使用 SQLAlchemy 和 SQLite3 存储字典
- laravel - Laravel 7.x 在监听器中使用构造变量调用控制器方法
- java - 堆内存超过阈值后的 Java 垃圾收集
- extjs - 无论如何可以从EXTJS中的实用程序类动态访问对象吗?
- html - 将自定义 HTML 表单链接到 Google 表单(如何处理日期输入?)
- java - Lambda 函数退出失败
- wordpress - 如何在 WPForms 插件表单 WordPress 中禁用滚动效果
- mongodb - Mongodb sh.status() 显示不存在的数据库和分片