繁体   English   中英

未捕获的类型错误:无法读取未定义的属性(读取“forEach”)-OpenWeather

[英]Uncaught TypeError: Cannot read properties of undefined (reading 'forEach') - OpenWeather

作为初学者,我正在 React 中开发一个天气应用程序项目。 在这种情况下,我使用的是 OpenWeatherAPI。

我的问题是当我尝试使用 forEach 时,它给出了一个错误,如下所示。

ApiCall.jsx:15 Uncaught TypeError: Cannot read properties of undefined (reading 'forEach')

这是我的 Header 组件:

import ApiCall from './ApiCall';

function Header() {
    const cities = ["İstanbul", "Ankara", "İzmir"]

    return (
        <div>
            <div className="header">
                <select name="selection">
                    <option value="istanbul">{cities[0]}</option>
                    <option value="ankara">{cities[1]}</option>
                    <option value="izmir">{cities[2]}</option>
                </select>
            </div>
            <ApiCall getCities={cities} />
        </div>   
    )

}

export default Header

这是我的 ApiCall 组件:

import axios from "axios"
import { useEffect, useState } from "react"

function ApiCall({ getCities }) {
    const[data, setData] = useState([])
    
    useEffect(() => {
        axios(`https://api.openweathermap.org/data/2.5/forecast?q=${selectCity}&appid=c681e6e33ec339728fdf88e0b24a2a01`)
        .then(res => setData(res.data))
        .catch(err=> console.log(err))
    })
    
    const { city, list } = data
    
    const selectCity = getCities.array.forEach((element) => {
        if (city.name === element) {
            return element
        }
    });

    return (
      null
    )
}

export default ApiCall

所有答案将不胜感激。

foreach 应该是这样的

getCities.forEach

代替

getCities.array.forEach

你怎么看?

如果 getCities 是一个数组,则必须在其上使用 forEach 而不是 using.array.forEach

似乎您尝试过滤所有可用城市以及您作为组件( getCities )的属性获得的城市。

由于getCities是一个数组,您可以直接在其上调用forEach function 并循环遍历城市,但由于您想应用过滤器,我认为您最好使用 Javascript 的内置过滤器方法。

const selectCity = getCities.filter((possibleCityName) => {
        return city.name === possibleCityName)
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM