javascript - 如何在 React 中每分钟自动获取数据?
问题描述
我想每分钟自动获取我的数据。我正在获取的数据是坐标。我想知道一个人的实时位置并打印坐标。现在,我有这个:
import React, { Component } from 'react';
class Test3 extends Component{
state = {
loading: true,
coordinates: null,
}
async componentDidMount(){
const url = "https://ttr.vsbbn.nl:4000/gps_history?team_id=10";
const response = await fetch(url);
const data = await response.json();
this.setState({coordinates: data, loading: false });
}
render(){
const { loading, coordinates } = this.state
return(
<div>
{loading || !coordinates ? (
<div>loading...</div>
) : (
<div>
{coordinates.map((coordinate, index) => {
return (
<div key={index}>
<p>Longitute: {coordinate.lon}</p>
<p>Latitude: {coordinate.lat}</p>
<p>Time: {coordinate.timestamp}</p>
<p>...............</p>
</div>
)
})}
</div>
)}
</div>
)
}
}
export default Test3;
有没有可能在应用程序中构建它?
解决方案
一种方法是使用这种方法:
import React, { Component } from 'react';
class Test3 extends Component{
state = {
loading: true,
coordinates: null,
}
intervalId = null;
fetchData = async () => {
const url = "https://ttr.vsbbn.nl:4000/gps_history?team_id=10";
const response = await fetch(url);
const data = await response.json();
this.setState({coordinates: data, loading: false });
}
async componentDidMount(){
await this.fetchData();
this.intervalId = setInterval(() => {
this.fetchData();
}, 1000 * 60)
}
componentWillUnmount() {
clearInterval(this.intervalId)
}
render(){
const { loading, coordinates } = this.state
return(
<div>
{loading || !coordinates ? (
<div>loading...</div>
) : (
<div>
{coordinates.map((coordinate, index) => {
return (
<div key={index}>
<p>Longitute: {coordinate.lon}</p>
<p>Latitude: {coordinate.lat}</p>
<p>Time: {coordinate.timestamp}</p>
<p>...............</p>
</div>
)
})}
</div>
)}
</div>
)
}
}
export default Test3;
推荐阅读
- javascript - Google Apps 脚本文件上传、保存到 Google 表格、无文件提交表单
- javascript - 使用jquery 动态颜色选择器?
- android - 伪本地化在语言中找不到英语 (XA)
- r - R中有没有办法计算两个不同事件之间的事件发生次数?
- reactjs - 如何将我的反应代码移植到移动应用程序中
- pentaho - 读取数据到表输入 pentaho
- r - 是否有任何方法专门替换 R 中的重复模式?
- python - Python flask @app.errorhandler(Exception) 得到完整的错误,而不仅仅是描述
- python - Python,作为函数参数的用户输入不起作用:TypeError:'str' object is not callable
- r - 如何使 geom_sf() 指向北?