reactjs 为什么在react中从对象析构嵌套数组时会出现错误

azpvetkf  于 2023-03-08  发布在  React
关注(0)|答案(3)|浏览(142)

我尝试访问存储在对象数据中的嵌套数组中的数据。此数据是通过“useContext”钩子从API获取的。在编写用于访问数据的代码后刷新时,它给我错误“未捕获的TypeError:无法读取undefined的属性(阅读'forecastday')”,但当尝试在vanilla js中访问它时,它显示在我的控制台上。现在不知道我的代码中到底发生了什么。但我觉得这里我猜我的Context.jsx页面中有问题。

对象数据

weatherReport = {
      "location": {object Data},
      "current": {object Data},
      "forecast": {
        "forecastday": [
          {
            "date": "2023-03-07",
            "date_epoch": 1678147200,
            "day": {
              "maxtemp_c": 36.1,
              "maxtemp_f": 97.0,
              "mintemp_c": 17.4,
              "mintemp_f": 63.3,
              "avgtemp_c": 25.6,
              "avgtemp_f": 78.1,
              "maxwind_mph": 9.6,
              "maxwind_kph": 15.5,
              "totalprecip_mm": 0.0,
              "totalprecip_in": 0.0,
              "totalsnow_cm": 0.0,
              "avgvis_km": 10.0,
              "avgvis_miles": 6.0,
              "avghumidity": 22.0,
              "daily_will_it_rain": 0,
              "daily_chance_of_rain": 0,
              "daily_will_it_snow": 0,
              "daily_chance_of_snow": 0,
              "condition": {
                "text": "Sunny",
                "icon": "//cdn.weatherapi.com/weather/64x64/day/113.png",
                "code": 1000
              },
              "UV": 7.0
            },
        },
}

React组件代码

import { useGlobalContext } from "../context"

const ForecastReport = () => {
  const { forecast: { forecastday: [...forecastday] } } = useGlobalContext()

  console.log(forecastday)

  return <div className="forecast-box">
    Forecast Report
  </div>
}

export default ForecastReport

控制台出错

"Uncaught TypeError: Cannot read properties of undefined (reading 'forecastday')

香草js

const {forecast:{forecastday:[...forecastday]}} = weatherReport

    console.log(forecastday);

vanilla js的控制台

(7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]

[https://replit.com/@djbravo12/WeatherApplicationOpenWeatherorg#src/context.jsx](我的回复链接)

dpiehjr4

dpiehjr41#

它会得到错误,因为当你的页面刷新或呈现时,时间上下文数据不会在上下文状态中设置,所以。它会得到**“未捕获的TypeError:无法读取未定义”**“的属性
您需要在存储上下文状态值时写入条件,然后才能访问它。

ctehm74n

ctehm74n2#

forecast可能还不可用,因此您会遇到未定义的问题。
在确认定义了forecast之后,尝试在useEffect钩子中更新。
你可以这样做:

import { useState, useEffect } from "react";
import { useGlobalContext } from "../context";

const ForecastReport = () => {
  const { forecast } = useGlobalContext();
  const [forecastDay, setForecastDay] = useState(null);

  useEffect(() => {
    if (forecast) {
      setForecastDay(forecast.forecastday);
    }
  }, [forecast]);

  return (
    <div className="forecast-box">
      Forecast Report
    </div>
  );
};

一旦forecastDay的值从null更改,您就可以对forecastDay执行任何操作。

o7jaxewo

o7jaxewo3#

我敢肯定,这个问题的发生是因为你的上下文。所以当你分享你的上下文代码时,它会更清楚。
顺便说一句,我已经在我这边测试过了。但是效果都很好。
这是我的代码(应用程序和数据组件)。

// import context
import { DataContextProvider, useData } from "./contexts/DataContext";

const Data = () => {
  const {
    people: {
      users: [...usersInfo],
    },
  } = useData();
  console.log(usersInfo);
  return <div>hello Data</div>;
};

const App = () => {
  return (
    <div className="App">
      <DataContextProvider>
        <Data />
      </DataContextProvider>
    </div>
  );
};

export default App;

下面是我的数据上下文代码。

import { createContext, useContext } from "react";

const initialData = {
  type: "chat",
  people: {
    users: [
      {
        name: "Kevin",
      },
      {
        name: "Rebecca",
      },
      {
        name: "Pavlo",
      },
    ],
  },
};

const dataContext = createContext();

const useData = () => useContext(dataContext);

const DataContextProvider = ({ children }) => {
  return (
    <dataContext.Provider value={initialData}>{children}</dataContext.Provider>
  );
};

export { DataContextProvider, useData };

希望这会有帮助。

相关问题