React无法读取未定义的属性

问题描述 投票:0回答:1

我是初学者,收到此错误“react-dom_client.js?v=10bcf841:19407 Uncaught TypeError: Cannot read properties of undefined (reading 'name') at WeatherCard (App.jsx:90:34)”。

/* eslint-disable react/prop-types */
import { useState } from "react";
import myImage from "./images/images.jpg";


const App = () => {
  const [apiData, setApiData] = useState({});
  const apiFetching = async (url) => {
    try {
      const response = await fetch(url);
      const data = await response.json();
      setApiData(() => data);
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };
  return (
    <>
      <Form apiFetching={apiFetching} />

      <WeatherCard data={apiData} />
    </>
  );
};

const Form = ({ apiFetching }) => {
  const [searchCity, setSearchCity] = useState("");
  const BASE_URL = `https://api.openweathermap.org/data/2.5/weather?q=`;

  const handleSubmit = (e) => {
    e.preventDefault();
    apiFetching(
      `${BASE_URL}${searchCity}&appid=(my api key: note code)`
    );
    setSearchCity("");
  };

  return (
    <form onSubmit={(e) => handleSubmit(e)}>
      <input
        type="text"
        value={searchCity}
        onChange={(e) => setSearchCity(e.target.value)}
        className="search-bar"
        placeholder="Enter city name..."
      />
      <button className="search-btn" type="submit">
        Search
      </button>
    </form>
  );
};

const WeatherCard = ({ apiData }) => {
  const staticData = {
    coord: { lon: 97.0333, lat: 20.7833 },
    weather: [
      { id: 800, main: "Clear", description: "clear sky", icon: "01n" },
    ],
    base: "stations",
    main: {
      temp: 284.9,
      feels_like: 284.01,
      temp_min: 284.9,
      temp_max: 284.9,
      pressure: 1015,
      humidity: 72,
      sea_level: 1015,
      grnd_level: 860,
    },
    visibility: 10000,
    wind: { speed: 0.89, deg: 233, gust: 0.95 },
    clouds: { all: 0 },
    dt: 1705756015,
    sys: { country: "MM", sunrise: 1705709452, sunset: 1705749237 },
    timezone: 23400,
    id: 1293960,
    name: "Taunggyi",
    cod: 200,
  };

  return (
    <div className="card-container">
      <div className="card">
        <div className="image-container">
          <img className="weather-img" src={myImage} alt="Images" />
        </div>
        <div className="info-container">
          <p>City Name: {apiData.name}</p>
          <p>Temperature in Kelvin: {apiData.main.temp} K</p>
          <p>
            Temperature in Celcius: {(apiData.main.temp - 273).toFixed(2)} °C
          </p>
          <p>
            Temperature in Fahrenheit:{" "}
            {(((apiData.main.temp - 273) * 9) / 5 + 32).toFixed(2)} °F
          </p>
          <p>Humidity: {apiData.main.humidity}%</p>
          <p>Pressure: {apiData.main.pressure}hPa</p>
          <p>Wind Speed: {apiData.wind.speed} m/s</p>
        </div>
      </div>
    </div>
  );
};
export default App;

我尝试询问 chat gpt 和 goggling,但没有成功。我检查了所有内容,但不知道有错误。这是错误代码“react-dom_client.js?v=10bcf841:14034 组件中发生上述错误:at WeatherCard (http://localhost:5173/src/App.jsx?t=1705834027751:95:24)在应用程序(http://localhost:5173/src/App.jsx?t=1705834027751:23:33)在WeatherCard(App.jsx:90:34)“

reactjs react-hooks components
1个回答
0
投票

您的

WeatherCard
组件正在访问
apiData
,但仅当用户提交
apiData
组件时,您的
Form
状态才会被设置值。当用户没有提交表单时,
apiData
保持为空,或者换句话说
undefined

由于没有

apiData
可供
WeatherCard
渲染,因此会抛出该错误。为了确保不会发生此错误,您可以将
apiData.name
apiData.main.temp
等替换为
apiData?.name
apiData?.main?.temp

这会检查

apiData
是否已定义(注意
?
),然后才访问它的属性。这样它就不会抛出您所看到的错误,因为它不会尝试访问访问时不存在的内容。

© www.soinside.com 2019 - 2024. All rights reserved.