gpt4 book ai didi

javascript - React 如何每分钟自动取数据?

转载 作者:行者123 更新时间:2023-12-04 00:59:43 25 4
gpt4 key购买 nike

我想每分钟自动获取我的数据。我正在获取的数据是坐标。我想知道一个人的实时位置并打印坐标。现在,我有这个:

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 - React 如何每分钟自动取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59631152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com