Next.how我可以修复js API请求后分配的数据中的推送错误吗

j1dl9f46  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(95)

我有一个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>
  );
};
ct3nt3jp

ct3nt3jp1#

为了避免posh错误,如果数组没有定义,则为其分配一个空数组。
像这样修改你的代码:

"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];
            if(!updatedForecast[updatedForecast.length - 1]){
                updatedForecast[updatedForecast.length - 1] = [];
            }
            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>
    );
};

相关问题