开发者问题收集

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

2022-02-11
251

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

CityCard

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>

  );
}
1个回答

问题

初始 forecast 状态声明为数组:

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

并传递给 CityCard 上的 forecast 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/未定义的属性。

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 响应

Drew Reese
2022-02-11