我有一个nextjs应用程序,在这个应用程序中,我有一个来自开放天气API的获取操作,我通过将其定义为[data = list]来完成。但是它给了我{TypeError:无法读取未定义的属性(阅读“push”)}错误我该怎么办。
"use client";
import React, { useState } from "react";
const ForecastDay = ({ data }) => {
const { list } = data;
let currentDate = list[0].dt_txt.split(" ")[0];
const [fiveDayForecast, setFiveDayForecast] = useState([]);
list.forEach((forecast) => {
const forecastDate = forecast.dt_txt.split(" ")[0];
if (forecastDate !== currentDate) {
setFiveDayForecast((prevForecast) => [...prevForecast, []]);
currentDate = forecastDate;
}
setFiveDayForecast((prevForecast) => {
const updatedForecast = [...prevForecast];
updatedForecast[updatedForecast.length - 1].push(forecast);
return updatedForecast;
});
});
return (
<div>
{fiveDayForecast.map((day, index) => (
<div key={index}>
<h2>Günün Tarihi: {day[0].dt_txt.split(" ")[0]}</h2>
{day.map((forecast) => (
<div key={forecast.dt}>
<p>Saat: {forecast.dt_txt.split(" ")[1]}</p>
<p>Sıcaklık: {forecast.main.temp}°F</p>
</div>
))}
</div>
))}
</div>
);
};
1条答案
按热度按时间ct3nt3jp1#
为了避免posh错误,如果数组没有定义,则为其分配一个空数组。
像这样修改你的代码: