我有一个JSON,如下所示:
{
"cod":"200",
"message":0,
"cnt":40,
"list":[
{
"dt":1601024400,
"main":{
"temp":301.11,
"feels_like":301.34,
"temp_min":301.11,
"temp_max":301.2,
"pressure":1010,
"sea_level":1010,
"grnd_level":907,
"humidity":58,
"temp_kf":-0.09
},
"weather":[
{
"id":803,
"main":"Clouds",
"description":"broken clouds",
"icon":"04d"
}
],
"clouds":{
"all":68
},
"wind":{
"speed":4.24,
"deg":238
},
"visibility":10000,
"pop":0.25,
"sys":{
"pod":"d"
},
"dt_txt":"2020-09-25 09:00:00"
}
]
} 我编写了一个React代码来提取数据。
代码:
import React from 'react';
// async
import { useAsync } from 'react-async';
const loadUsers = async () =>
await fetch("http://api.openweathermap.org/data/2.5/forecast?q=bengaluru&appid={API_KEY}")
.then(res => (res.ok ? res : Promise.reject(res)))
.then(res => res.json())
export default function Dashboard() {
const { data, error, isLoading } = useAsync(
{
promiseFn: loadUsers
}
)
if (isLoading) return "Loading..."
if (error) return `Something went wrong: ${error.message}`
console.log("Data is", data)
if (data)
return (
<div className="container">
<div className="App">
<h2>Weather Details</h2>
</div>
{data.list.map((weather, index) => (
<div key={index} className="row">
<div className="col-md-12">
<p>{weather.temp_min}</p>
<p>{weather.temp_max}</p>
</div>
</div>
))}
</div>
)
} 但它是空的,如这里所示..。

我怎么才能提取数据?
发布于 2020-09-25 16:57:50
我不确定你的数据是否真的被拉到了前端,但如果是的话,我认为问题是当你对它进行映射时。当您使用data.list.map((weather, index) => (时,在该实例中,weather是list中的每个项。因此,我认为您正在寻找的不是weather.min_temp (它并不存在),而是weather.main.min_temp和weather.main.max_temp。
{data.list.map((weather, index) => (
<div key={index} className="row">
<div className="col-md-12">
<p>{weather.main.temp_min}</p>
<p>{weather.main.temp_max}</p>
</div>
</div>
))}另外,不建议将索引用作key。也许dt是一个独特的值,您可以使用它作为键吗?
https://stackoverflow.com/questions/64068270
复制相似问题