【问题标题】:TypeError: Cannot read property 'country' of undefinedTypeError:无法读取未定义的属性“国家”
【发布时间】:2020-09-15 17:30:55
【问题描述】:

我正在尝试从 API 获取数据并在我的应用中使用该数据。但问题是,当我尝试从我刚刚从 API 获得的 JSON 中获取某些对象或数据时,我得到 TypeError: Cannot read property 'country' of undefined。
属性确实存在。
顺便说一句,我正在使用 React.js。
非常感谢您的帮助和指导。
这是代码:

App.js

import React, {useEffect, useState} from 'react';
import './App.css';
import Navigation from "./components/Navigation/Navigation";
import Forecast from "./components/forecast/forecast";
// function

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            responseFromAPI: {},
        }
    }

    getPosition = function () {
        return new Promise(function (resolve, reject) {
            navigator.geolocation.getCurrentPosition(resolve, reject);
        });
    }
    getWeather = async function (latitude, longtitude) {
        const One_weather_call = await fetch(`https://community-open-weather-map.p.rapidapi.com/weather?lat=${latitude}&lon=${longtitude}&units=metric`,
            {
                "method": "GET",
                "headers": {
                    "x-rapidapi-host": "some private info here",
                    "x-rapidapi-key": "some private info here"
                }
            }).then(response => response.json());

        console.log("fetch data");
        return One_weather_call;

    };

    componentDidMount() {
        this.getPosition()
            .then(position => {
                this.getWeather(position.coords.latitude, position.coords.longitude)
                    .then(res => {this.setState({responseFromAPI: res});
                    });
            });

        console.log("after setting response in app.js ", this.state.responseFromAPI);


    };

    render() {
        return (
            <React.Fragment>
                <Navigation city={this.state.responseFromAPI.name}

                            country={this.state.responseFromAPI.sys.country}
                />

            </React.Fragment>
        );
    };
}

export default App;

JSON

{"coord": { "lon": 139,"lat": 35},
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 281.52,
    "feels_like": 278.99,
    "temp_min": 280.15,
    "temp_max": 283.71,
    "pressure": 1016,
    "humidity": 93
  },
  "wind": {
    "speed": 0.47,
    "deg": 107.538
  },
  "clouds": {
    "all": 2
  },
  "dt": 1560350192,
  "sys": {
    "type": 3,
    "id": 2019346,
    "message": 0.0065,
    "country": "JP",
    "sunrise": 1560281377,
    "sunset": 1560333478
  },
  "timezone": 32400,
  "id": 1851632,
  "name": "Shuzenji",
  "cod": 200
}

如您所见,此 JSON 数据中的国家/地区的位置如下 json.sys.country 但我这样会出错。但是当我尝试访问json.main等其他变量时没有错误。

【问题讨论】:

  • 在 Ajax 请求完成之前,数据不存在。您需要在构造函数中包含this.state = { responseFromAPI: null } 并放入if(!this.state.responseFromAPI) { return &lt;div&gt;Loading...&lt;/div&gt;; } 或类似于渲染函数的内容。
  • 另外,您可以在正在访问的状态属性上使用可选链接,即this.state.responseFromAPI?.sys?.country,但请注意这可能会将undefined 传递给子组件,因此它也需要能够处理它.
  • @GuyIncognito ajax 完成,将 JSON 数据设置为 responseFromAPI 没有问题,问题是,在这种情况下,我不能只获得指定的数据,即国家/地区。唯一的问题是国家,我可以得到其余的数据。 country 本身在 json 中可用。
  • 这是因为this.state.responseFromAPI最初是一个定义的对象,所以在获取数据之前的初始渲染期间访问this.state.responseFromAPI.name是可以的并返回undefined,就像你访问this.state.responseFromAPI.sys一样,它返回未定义,但是当您尝试访问this.state.responseFromAPI.sys 中的country 时,您正在访问未定义对象的属性,这将引发错误。
  • 同样,问题是渲染函数在 Ajax 完成之前运行。

标签: javascript reactjs api fetch openweathermap


【解决方案1】:

最后,我设法通过有条件地设置 render() 函数中的组件的 props 来解决问题,如下所示:

  render() {
        return (
            <React.Fragment>

                <Navigation city={this.state.responseFromAPI ? this.state.responseFromAPI.name : ""}

                            country={this.state.responseFromAPI ? this.state.responseFromAPI.sys.country
                            : "Loading"}
                />

            </React.Fragment>
        );
    };

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 2022-07-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多