问题描述
我正在尝试制作一个反应组件,该组件在安装时每 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 (将#修改为@)