简单的天气应用程序在 weather.main.temp 变量处中断

Simple weather app breaking at weather.main.temp variable

我正在使用 React hooks、codesandbox.io 和 OpenWeatherAPI 构建一个非常基本的天气应用程序。 它在 const temp = forecast.main.temp; 处中断并返回“TypeError:无法读取未定义的属性(读取 'temp')” 当我最初编写它时它实际上确实 运行 但如果我添加另一个变量或必须以任何方式编辑临时变量。

import React, { useState } from "react";
import "../styles.css";
import CityCard from "./cityCard";

export default function GetWeather() {

  const [city, setCity] = useState('');
  const [forecast, setForecast] = useState([]);

  const getCity = async (e) => {
    e.preventDefault();

  //API variables 
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperial&appid=${APIkey}`;
  
  //fetch response
  try {
  const res = await fetch(url);
  const data = await res.json();
  setForecast(data);
  } catch (err) {
    console.error(err);
  }

};

  return (
    //basic input form to search by city
    <div>
      <h1 className="title">Weather App</h1>
      <CityCard forecast={forecast} />
      <form className="form" onSubmit={getCity}>
      <label className="label" htmlFor="city">
      <p>Search by City</p>
      </label>
      <input 
        className="input" 
        type="text" 
        name="query place"
        placeholder="i.e. Seattle"
        value={city} onChange={(e) => setCity(e.target.value)}
        >
      </input>
      <button 
      className="button" 
      type="submit"
      >Search</button>
      </form>
    </div>
  );
}

城市卡

import React from "react";
import "../../src/styles.css";

export default function CityCard({ forecast }) {
  //pass props to cards
  const cityName = forecast.name;
  const temp = forecast.main.temp;

  return (
      <div className="card-container">
        <p className="card-title">{cityName}</p>
        <p>Temp: {temp} </p>
      </div>

  );
}

问题

初始forecast状态声明为数组:

const [forecast, setForecast] = useState([]);

并在 forecast 上传递给 CityCard prop:

<CityCard forecast={forecast} />

然后像访问对象一样访问:

function CityCard({ forecast }) {
  //pass props to cards
  const cityName = forecast.name;  // OK, undefined
  const temp = forecast.main.temp; // Not OK, can't access temp of undefined

  return (
      <div className="card-container">
        <p className="card-title">{cityName}</p>
        <p>Temp: {temp}</p>
      </div>

  );
}

解决方案

使用可选链接运算符来防止 null/undefined 属性 访问。

function CityCard({ forecast }) {
  //pass props to cards
  const cityName = forecast?.name;
  const temp = forecast?.main?.temp;

  return (
      <div className="card-container">
        <p className="card-title">{cityName}</p>
        <p>Temp: {temp}</p>
      </div>

  );
}

或者在有有效的 forecast 数据要显示时等待呈现 CityCard

const [forecast, setForecast] = useState();

...

{forecast?.name && forecast?.main?.temp && <CityCard forecast={forecast} />}

OpenWeather JSON API response