开发者问题收集

React.js 与 OpenWeatherMap 结合,获取 weathers.map 不是一个函数

2022-03-04
341

我正在学习上大学的React.js,并且有点困扰。我遇到此错误:

074042406

我确定它很简单,但无法弄清楚!它是标准 create-react-app ,创建一个称为组件的目录,这两个文件现场存在:

weathers.js:

585152672

天气:

822173720
2个回答

您收到错误是因为 api 的结果不是数组。它是一个如下所示的对象(对于伦敦):

{
    "coord": {
        "lon": -0.1257,
        "lat": 51.5085
    },
    "weather": [
        {
            "id": 500,
            "main": "Rain",
            "description": "light rain",
            "icon": "10n"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 278.91,
        "feels_like": 276.51,
        "temp_min": 277.25,
        "temp_max": 280.02,
        "pressure": 1021,
        "humidity": 88
    },
    "visibility": 10000,
    "wind": {
        "speed": 3.09,
        "deg": 330
    },
    "rain": {
        "1h": 0.89
    },
    "clouds": {
        "all": 100
    },
    "dt": 1646438029,
    "sys": {
        "type": 2,
        "id": 2019646,
        "country": "GB",
        "sunrise": 1646375984,
        "sunset": 1646415906
    },
    "timezone": 0,
    "id": 2643743,
    "name": "London",
    "cod": 200
}

如果您想要结果中的 name 属性,您可以像这样获取它:

import {useState} from 'react'
import axios from 'axios'
import Weather from './Weather'

function Weathers() {
    const [weathers, setWeathers] = useState()
    const [city, setCity] = useState('')
    const API = {
    link: "http://api.openweathermap.org/data/2.5/weather?q=",
    key: "&appid=xxxxx"
    }

    function handleSearchCity(e) {
        e.preventDefault()
        setCity(e.target.value)
    }

    async function searchWeathers(e) {
        e.preventDefault()
        console.log()
        var response = await axios.get(API.link + city + API.key)
        console.log(response)
        setWeathers(response.data)
    }
    
    return (
       <div>
         <input value={city} onChange={handleSearchCity} />
         <button onClick={searchWeathers}>Search</button>
         {weathers && <Weather name={weathers.name} />}
       </div> 
    )
}
export default Weathers;
Youssouf Oumar
2022-03-05

由于 weathers 被初始化为一个空数组,因此您实际上不应该收到错误 weathers.map 不是函数 。 也许您可以添加条件渲染,以便仅在从 API 获取天气数据时返回 jsx 表达式。

return weathers && (
        <div>
        // ...
        </div> 
    )
}
export default Weathers;
Ikdemm
2022-03-04