Необработанное отклонение (ошибка типа): не удается прочитать свойство ‘temp’ неопределенного

#reactjs #react-hooks #openweathermap #weather-api

#reactjs #реагирующие крючки #openweathermap #погода-api

Вопрос:

Мы создаем веб-сайт погоды с использованием React-hooks.

Api получил его из https://openweathermap.org/current#parameter .

Но я не могу прочитать свойства температуры.

Согласно описанию веб-сайта, main: main.temp Температура. Единица измерения по умолчанию: Кельвин, метрическая: Цельсий, имперская: Фаренгейт.

Не удается получить свойства внутри JSON

В чем причина?

Это мой файл Weather.jsx

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

const Weather = () => {
  const [weather, setWeather] = useState("");
  const [error, setError] = useState(null);
  const API_KEY = "1234567890"; // My Api key
  const COORDS = "coords";
  const baseUrl = "https://api.openweathermap.org/data/2.5/";

  const getWeather = (lat, lon) => {
    fetch(
      `${baseUrl}weather?lat=${lat}amp;lon=${lon}amp;appid=${API_KEY}amp;units=metricamp;lang={kr}`
    )
      .then(function (response) {
        return response.json();
      })
      .then(function (json) {
        const temperature = json.main.temp; // Error part!!!
        const place = json.name;
        setWeather(`${temperature} n ${place}`);
      });
  };
  useEffect(() => {
    getWeather();
  }, []);
  const saveCoords = (coordsObj) => {
    localStorage.setItem(COORDS, JSON.stringify(coordsObj));
  };

  const weatherSuccess = (position) => {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    const coordsObj = {
      latitude: latitude,
      longitude: longitude,
    };
    saveCoords(coordsObj);
    getWeather(latitude, longitude);
  };

  const weatherError = () => {
    setError("위치 정보를 얻을 수 없습니다.");
  };

  const askForCoords = () => {
    navigator.geolocation.getCurrentPosition(weatherSuccess, weatherError);
  };

  const loadCoords = () => {
    const loadedCoords = localStorage.getItem(COORDS);
    if (loadedCoords === null) {
      askForCoords();
    } else {
      const parsedCoords = JSON.parse(loadedCoords);
      getWeather(parsedCoords.latitude, parsedCoords.longitude);
    }
  };
  const init = () => {
    loadCoords();
  };
  init();

  return weather;
};
export default Weather;

 

Этот файл Weather.jsx отображается в файле Presenter.jsx.

 import React from "react";
import styled from "styled-components";
import Weather from "../../Components/Weather";

const DetailPresenter = () => {
  
  return (
    <>
      <DetailContainer>
        <Weather/>  
      </DetailContainer> 
    </>
  );
};
export default DetailPresenter;
 

Просмотреть полный код https://github.com/eunjin0212/React-KakaoClone/issues/2

консоль.результат журнала 👇

 {coord: {…}, weather: Array(1), base: "stations", main: {…}, visibility: 10000, …}
base: "stations"
clouds: {all: 0}
cod: 200
coord: {lon: 126.79, lat: 37.65}
dt: 1608189833
id: 1842485
main: {temp: 0.08, feels_like: -4.98, temp_min: -1, temp_max: 1, pressure: 1030, …}
name: "Goyang-si"
sys: {type: 1, id: 8105, country: "KR", sunrise: 1608158521, sunset: 1608192958}
timezone: 32400
visibility: 10000
weather: [{…}]
wind: {speed: 2.1, deg: 300}
__proto__: Object
-----
{cod: "400", message: "wrong latitude"}
cod: "400"
message: "wrong latitude"
__proto__: Object
 

Комментарии:

1. Какова форма ответа JSON? Можете ли вы включить это в свой вопрос? Все, что говорит об ошибке, это то, что json.main не определено, поэтому данные, которые вы пытаетесь получить, возможно, вложены в другое место.

2. @DrewReese Я включаю это

3. Это то, что API говорит, что возвращает. Какой ответ вы на самом деле получаете? Проверьте вкладку «Сеть» в инструментах разработчика вашего браузера, установите точку останова в const temperature = json.main.temp; строке или console.log(json) перед ней, чтобы узнать, какое значение имеет ваш код во время выполнения.

4. Я добавил результат.

5.В этом и заключается ценность json незадолго до const temperature = json.main.temp; этого? Это совсем не похоже на правду.