我获取一些日期并获取数组,我可以console.log并查看所有人员,但是当我尝试映射或访问数组中的某些元素时出现错误undefined ...
得到这个 未处理的拒绝(TypeError):无法读取未定义的属性“地图”
const [key, setKey] = useState(false);
const [country, setCountry] = useState([]);
const [nextFive, setFive] = useState([]);
useEffect(() => {
getWeather();
}, [key]);
const getCity = async (e) => {
e.preventDefault();
const cityName = e.target.elements.cityName.value;
const api_call = await fetch(`http://dataservice.accuweather.com/locations/v1/cities/search?apikey=${process.env.REACT_APP_WEATHER_API_KEY}&q=${cityName}&details=true`);
const data = await api_call.json();
setKey(data[0].Key);
setCountry(data[0]);
return data[0].Key;
}
const getWeather = async (cityKey = key) => {
const proxy = `https://cors-anywhere.herokuapp.com/`;
const link = `${proxy}http://dataservice.accuweather.com/forecasts/v1/daily/5day/${cityKey}?apikey=${process.env.REACT_APP_WEATHER_API_KEY}&details=true&metric=true`;
const api_call = await fetch(link);
const data = await api_call.json();
setFive(data.DailyForecasts);
};
console.log(nextFive); if i tray console.log(nextFive[0].something) i will get error :)
console.log(country);
{
nextFive.map((item) => {
return <p>{item.Date}</p>
})
}
并获得此未处理的拒绝(TypeError):无法读取未定义的属性“ map”
答案 0 :(得分:0)
发生这种情况的原因是,您尝试显示数组中尚未填充的项目的第一个元素。
您可能有一个名为 weatherLoading 的额外钩子,一旦api调用成功,您就可以将weatherLoading的状态设置为true,然后只需执行以下操作:
weatherLoading && console.log(nextFive[0].something)