简体   繁体   English

使用 openweather API “TypeError: Cannot read properties of undefined (reading 'temp')”做出反应时出错

[英]Getting an error in react using openweather API "TypeError: Cannot read properties of undefined (reading 'temp')"

HERE IS THE REACT CODE这是反应代码

 import React, { useEffect, useState } from "react"; import "./css/style.css"; import { BiStreetView } from "react-icons/bi"; const Tempapp = () => { const [city, setCity] = useState(null); const [search, setSearch] = useState(""); useEffect(() => { try { const fetchApi = async () => { const url = `https://api.openweathermap.org/data/2.5/weather?q=${search}&units=metric&appid=83ea3057047027c6c4521d32d69250a0`; const res = await fetch(url); const resjson = await res.json(); setCity(resjson); }; fetchApi(); } catch (error) { console.log(error); } }, [search]); return ( <> <div className="box"> <div className="inputData"> <input type="search" className="inputFeild" value={search} placeholder="Enter city" onChange={(event) => { setSearch(event.target.value); }} /> </div> {?city: ( <p>Enter city or country to know weather</p> ). ( <div> <div className="info"> <img src="../images/weather.png" alt="image" className="info-img" /> <h3 className="dateTime">{date}</h3> <h3 className="dateTime">{time}</h3> <h2 className="location"> <BiStreetView className="location-icon" /> {search} </h2> <h1 className="temp">{city.main:temp} °Cel</h1> <h3 className="tempmin_max"> Min. {city.main:temp_min} °Cel | Max. {city.main;temp_max} °Cel </h3> </div> <div className="wave -one"></div> <div className="wave -two"></div> <div className="wave -three"></div> </div> )} </div> </> ); }; export default Tempapp;

AND HERE IS THE API DATA.这是 API 数据。 AND I WANT TO USE THE MAIN PART AND WEATHER PART OF DATA.我想使用数据的主要部分和天气部分。

and I want to get the temperature, temp_min, temp_max from main object and main from the weather array.我想从主 object 和天气数组中获取温度 temp_min 和 temp_max。 I am getting error called cannot read property of undefined reading "temp".我收到错误,称为无法读取未定义读取“temp”的属性。 please someone solve this.请有人解决这个问题。

{
  "coord": {
    "lon": 73.8333,
    "lat": 15.4833
  },
  "weather": [{
    "id": 804,
    "main": "Clouds",
    "description": "overcast clouds",
    "icon": "04n"
  }],
  "base": "stations",
  "main": {
    "temp": 298.95,
    "feels_like": 299.75,
    "temp_min": 298.95,
    "temp_max": 298.95,
    "pressure": 1011,
    "humidity": 83,
    "sea_level": 1011,
    "grnd_level": 1011
  },
  "visibility": 10000,
  "wind": {
    "speed": 2.94,
    "deg": 303,
    "gust": 4.1
  },
  "clouds": {
    "all": 86
  },
  "dt": 1663596174,
  "sys": {
    "country": "IN",
    "sunrise": 1663548808,
    "sunset": 1663592632
  },
  "timezone": 19800,
  "id": 1260607,
  "name": "Panjim",
  "cod": 200
}

Below is the working version of your app.以下是您的应用程序的工作版本。 Try using optional chaining for your async datas while reading them.在读取异步数据时尝试使用可选链接。 Plus, you should consider why you need useEffect which has search dependency that rerenders your component.另外,您应该考虑为什么需要 useEffect ,它具有重新呈现您的组件的搜索依赖项。

import React, { useEffect, useState } from 'react';

const Tempapp = () => {
  const [city, setCity] = useState('');
  const [search, setSearch] = useState('');
  const fetchApi = async () => {
    try {
      const url = `https://api.openweathermap.org/data/2.5/weather?q=${search}&units=metric&appid=83ea3057047027c6c4521d32d69250a0`;
      const res = await fetch(url);
      const data = await res.json();
      setCity(data);
    } catch (error) {
      console.log(error);
    }
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    fetchApi();
  };
  return (
    <>
      <div className="box">
        <form onSubmit={handleSubmit} className="inputData">
          <input
            type="search"
            className="inputFeild"
            value={search}
            placeholder="Enter city"
            onChange={(event) => {
              setSearch(event.target.value);
            }}
          />
          <button type="submit">Search</button>
        </form>
        {!city ? (
          <p>Enter city or country to know weather</p>
        ) : (
          <div>
            <div className="info">
              <img
                src="../images/weather.png"
                alt="image"
                className="info-img"
              />
              <h1 className="temp">{city?.main?.temp} °Cel</h1>

              <h3 className="tempmin_max">
                Min : {city.main?.temp_min} °Cel | Max : {city.main?.temp_max}{' '}
                °Cel
              </h3>
            </div>
            <div className="wave -one"></div>
            <div className="wave -two"></div>
            <div className="wave -three"></div>
          </div>
        )}
      </div>
    </>
  );
};

export default Tempapp;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获的类型错误:无法读取未定义的属性(读取“forEach”)-OpenWeather - Uncaught TypeError: Cannot read properties of undefined (reading 'forEach') - OpenWeather TypeError:无法读取未定义(读取“过滤器”)和未定义错误的属性 - React - TypeError: Cannot read properties of undefined (reading 'filter') and undefined error - React 我在 React 中收到“TypeError: Cannot read properties of undefined(reading: 0)” - I'm getting "TypeError: Cannot read properties of undefined(reading: 0)" in React 错误:TypeError:无法读取未定义的属性(读取“transformFile”)本机反应 - error: TypeError: Cannot read properties of undefined (reading 'transformFile') react native 在 reactjs TypeError 中出现错误:无法读取未定义的属性(读取“过滤器”) - Getting error in reactjs TypeError: Cannot read properties of undefined (reading 'filter') 反应:未处理的拒绝(TypeError):无法读取未定义的属性(读取“错误”) - React : Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'error') 反应错误:“TypeError:无法读取未定义的属性(读取'props')” - react error: "TypeError: Cannot read properties of undefined (reading 'props')" react-lazy-load-image-component 出现错误“TypeError:无法读取未定义的属性(读取'原型')” - react-lazy-load-image-component Getting Error "TypeError: Cannot read properties of undefined (reading 'prototype')" 在 React axios 方法中使用 Chartjs 时出现“Uncaught TypeError: Cannot read properties of undefined (reading 'map')” - Getting "Uncaught TypeError: Cannot read properties of undefined (reading 'map')" when using Chartjs inside react axios method 使用 ipcRenderer 时出现错误(类型错误无法读取未定义的属性(读取“发送”)) - I am getting an error when using ipcRenderer (typeerror cannot read properties of undefined (reading 'send'))
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM