reactjs - 数据不会被拉入前端 - 做出反应
问题描述
我有一个 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>
)
}
解决方案
我不确定您的数据是否真的被拉入前端,但如果是,我认为问题在于您何时映射它。当您使用data.list.map((weather, index) => (
时,在该实例weather
中是list
. 因此,而不是weather.min_temp
(不存在)我认为您正在寻找weather.main.min_temp
and 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>
))}
顺便说一句,不建议将 index 用作key
. 也许这dt
是一个可以用作键的唯一值?
推荐阅读
- docker - kafka消费者无法连接
- php - 在一定数量的列之后拆分html表
- java - 端点返回对象而不是直接 JSON
- java - 使用 Java 8 流查找数组中对角线元素的总和
- node.js - Sequelize where option sql injection?
- angular - 模板继承和/或组合
- sql-server-2008 - 如果值不为空,如何通过在每个值之间保留空格来将三列(nvarchar,null)合并为一列(nvarchar)?
- javascript - 将打字稿函数保存为对象变量(Angular 6)
- spring - 来自控制器类的另一个项目中的 Spring Boot 应用程序
- sql - SQL - 使用 CAST 将文本转换为位