首页 > 解决方案 > 数据不会被拉入前端 - 做出反应

问题描述

我有一个 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>
    )

}  

但它是空的,如此处所示...... 我怎样才能提取数据?
仪表盘

标签: reactjs

解决方案


我不确定您的数据是否真的被拉入前端,但如果是,我认为问题在于您何时映射它。当您使用data.list.map((weather, index) => (时,在该实例weather中是list. 因此,而不是weather.min_temp(不存在)我认为您正在寻找weather.main.min_tempand 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是一个可以用作键的唯一值?


推荐阅读