类型错误:无法读取未定义的属性“国家/地区”

问题描述 投票:0回答:1

我正在尝试从 API 获取数据并在我的应用程序中使用该数据。但问题是,当我尝试从刚刚从 API 获取的 JSON 中获取某些对象或数据时,我得到:

类型错误:无法读取未定义的属性“国家/地区”。

属性

DO 存在。 顺便说一句,我正在使用 React.js。
我非常感谢您的帮助和指导。
这是代码:

应用程序.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
)时没有错误。

javascript reactjs fetch-api openweathermap
1个回答
0
投票
最后,我通过有条件地设置

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> ); };
    
© www.soinside.com 2019 - 2024. All rights reserved.