首页 > 解决方案 > 无法获取来自 REACTJS 中 API 调用的对象的属性值

问题描述

为什么我无法访问来自 API 调用的对象的属性值?

我在 React 应用程序中有两个组件,两者都在下面给出。

这是名为“天气”的第一个组件

import React, { useState, useEffect } from "react";
import Styles from "./Weather.module.css";
import WeatherCard from "../Weather Card/WeatherCard.component";

const Weather = () => {
  // Initializing State
  //For Location
  const [location, setLocation] = useState("karachi");
  //For Location
  //For Query
  const [query, setQuery] = useState(location);
  //For Query
  //For Weather Data
  const [weatherData, setWeatherData] = useState({});

  //For Weather Data

  // Initializing State

  // Calling data through api

  useEffect(() => {
    const fetchingData = async () => {
      let url = `https://api.openweathermap.org/data/2.5/weather?q=${query}&appid=6a571911f99d7d02c4974a178ff1d933`;

      let responseFromFetch = await fetch(url); // getting obj of promise.

      let data = await responseFromFetch.json(); // getting api/weather data.

      setWeatherData(data); // setting state that comes from api.
    };

    fetchingData(); // calling func that brings the data
  }, [query]);

  const handleSubmit = (e) => {
    e.preventDefault();
    setQuery(location);
    setLocation("");
  };

  return (
    <>
      <div className={Styles.formContainer}>
        <form onSubmit={handleSubmit}>
          <input
            className={Styles.inputField}
            type="text"
            placeholder="Know Your City Weather!"
            value={location}
            onChange={(e) => setLocation(e.target.value)}
          />
          <button type="submit" className={Styles.button}>
            Search
          </button>
        </form>
      </div>

      <WeatherCard weatherData={weatherData} />
    </>
  );
};

export default Weather;

好的,现在这是名为“WeatherCard”的第二个组件

import React, { Component } from "react";
import Styles from "../Whether/Weather.module.css";

export default class WeatherCard extends Component {
  render() {
    const accessObj = this.props.weatherData;

    console.log(accessObj); // getting whole obj - No error,
    console.log(accessObj.name); // getting the value of the key "name" - No error,       accessObj.name isn't an object
    console.log(accessObj.sys); // getting obj - No error,          accessObj.sys is an object
    console.log(accessObj.sys.country); // Not getting the value of key "country" - Error

    if (accessObj !== "undefined") {
      return (
        <>
          <div className={Styles.wrapper}>
            <div className={Styles.weatherContainer}>
              <div className={Styles.cityContainer}>
                <p className={Styles.city}>{accessObj.name}</p>
              </div>

              <div className={Styles.countryContainer}>
                {/* I want here to use the value of the property... But country is not available here.  */}

                <p className={Styles.country}>{accessObj.sys.country}</p>
              </div>

              <div className={Styles.tempContainer}>
                <p className={Styles.temp}>30 C</p>
              </div>

              <div className={Styles.humidityContainer}>
                <p className={Styles.humidity}>100</p>
              </div>
            </div>
          </div>
        </>
      );
    }
  }
}

您还可以在浏览器中看到发生的错误。截图链接在这里。无法在此处附上错误截图,因为我是这个平台的新手! 在此处输入图像描述

提前感谢您的帮助!

标签: javascriptreactjsobject

解决方案


有时过于花哨会导致您遇到一些问题,例如这里的问题,基本上问题是您的 useEffect 挂钩具有 void 类型,因为它不返回任何内容。

...

const fetchingData = () => {
      let url = `https://api.openweathermap.org/data/2.5/weather?q=${query}&appid=6a571911f99d7d02c4974a178ff1d933`;

     return fetch(url)
        .then(res => res.json())
        .then(data => myFunctionThatSetsTheState(data)).catch(console.error)
};

useEffect(() => fetchingData(), [query]);

....

推荐阅读