gpt4 book ai didi

javascript - 如何使用react.js从REST API获取数据

转载 作者:行者123 更新时间:2023-11-28 03:16:23 25 4
gpt4 key购买 nike

API 中的数据如下所示:

[
{ "lon": "4,483792", "lat": "51,917029" },
{ "lon": "4,483792", "lat": "51,919029" },
{ "lon": "4,483892", "lat": "51,929029" },
{ "lon": "4,484892", "lat": "51,931029" },
{ "lon": "4,423892", "lat": "51,919400" },
{ "lon": "4,438892", "lat": "51,915322" },
{ "lon": "4,483092", "lat": "51,917500" },
{ "lon": "4,403892", "lat": "51,925029" }
]

如何将这些数据检索到我的 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=1";
const response = await fetch(url);
const data = await response.json();
this.setState({ coordinates: lon, loading: false });
}

render() {
return(
<div>
{this.state.loading || !this.state.coordinates ? (
<div>loading...</div>
) : (
<div>
<div>{this.state.lon}</div>
</div>
)}
</div>
)
}
}

export default Test3;

最佳答案

您几乎就得到了好的代码!如前所述,您需要使用名为 data 的正确数据 block 来设置状态:

const data = await response.json();
this.setState({coordinates: data, loading: false });

现在您可以使用 map() 方法迭代数据

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=1";
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>
</div>
)
})}
</div>
)}

</div>
)
}

}

export default Test3;

关于javascript - 如何使用react.js从REST API获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59604426/

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