[英]Uncaught TypeError: Cannot read properties of undefined (reading 'forEach') - OpenWeather
I am working on a weather app project in React as a beginner.作为初学者,我正在 React 中开发一个天气应用程序项目。 I am using OpenWeatherAPI in that case.
在这种情况下,我使用的是 OpenWeatherAPI。
My problem is when I try to use forEach, it gives an error as it seems below.我的问题是当我尝试使用 forEach 时,它给出了一个错误,如下所示。
ApiCall.jsx:15 Uncaught TypeError: Cannot read properties of undefined (reading 'forEach')
Here is my Header component:这是我的 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
And this is my ApiCall component:这是我的 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
All answers will be appreciated.所有答案将不胜感激。
The foreach should be like this foreach 应该是这样的
getCities.forEach
Instead of代替
getCities.array.forEach
What do you think?你怎么看?
If getCities is an array, you have to use forEach on it instead of using.array.forEach如果 getCities 是一个数组,则必须在其上使用 forEach 而不是 using.array.forEach
It seems that you try to filter all the available cities with the cities you are getting as property to your component ( getCities
).似乎您尝试过滤所有可用城市以及您作为组件(
getCities
)的属性获得的城市。
Since getCities
is an array you can directly call the forEach
function on it and loop over the cities but since you want to apply a filter I think you are better off using Javascript's build-in filter method.由于
getCities
是一个数组,您可以直接在其上调用forEach
function 并循环遍历城市,但由于您想应用过滤器,我认为您最好使用 Javascript 的内置过滤器方法。
const selectCity = getCities.filter((possibleCityName) => {
return city.name === possibleCityName)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.