[英]React TypeError undefined
我是 React 世界的新手。 我正在創建天氣應用程序,我正在使用 openweathermap api 來獲取數據(使用了黑暗的天空 api 並遇到了同樣的問題)。 問題是我獲取了一個獲取數據並將其保存到狀態。 我可以通過 JSX 和 console.log 打印該狀態的全部內容,但無法訪問內部的特定數據(通過 console.log 和 JSX)。 問題說: TypeError:無法讀取未定義的屬性“城市”
這是我的代碼:
import React from 'react';
import TemperaturesList from './TemperaturesList';
import axios from 'axios';
class WeatherData extends React.Component {
state = { weatherData: {}, error: null };
componentDidMount(){
axios.get('https://samples.openweathermap.org/data/2.5/forecast?lat=${this.props.lat}&lon=${this.props.long}&appid=MYAPPID')
.then(result => this.setState({
weatherData: result
}))
.catch(error => this.setState({
error: error
}))
}
render(){
return(
<div>
{JSON.stringify(this.state.weatherData)} // this works
<h3>Current weather:</h3>
{JSON.stringify(this.state.weatherData.data.city)} // this does not work
</div>
);
};
};
export default WeatherData;
這是我從 fetch 和 save in state 中得到的:
在componentDidMount
從服務器獲取數據之前,React 將嘗試呈現當前處於狀態的內容:
state = { weatherData: {}, error: null };
....
{JSON.stringify(this.state.weatherData.data.city)}
此時, weatherData
是一個空對象。
您可以通過在狀態中設置data
來修復它:
state = { weatherData: { data: {} }, error: null };
api 調用將在render
后觸發,因此this.state.weatherData.data
在初始渲染時將是未定義的。 此外,最好將 axios response.data
存儲在狀態而不是整個響應本身。 這應該工作
import React from 'react';
import TemperaturesList from './TemperaturesList';
import axios from 'axios';
class WeatherData extends React.Component {
state = { weatherData: {city: ''}, error: null };
componentDidMount(){
axios.get('https://samples.openweathermap.org/data/2.5/forecast?
lat=${this.props.lat}&lon=${this.props.long}&appid=MYAPPID')
.then(result => this.setState({
weatherData: result.data
}))
.catch(error => this.setState({
error: error
}))
}
render(){
return(
<div>
{JSON.stringify(this.state.weatherData)}
<h3>Current weather:</h3>
{JSON.stringify(this.state.weatherData.data.city)}
</div>
);
};
};
export default WeatherData;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.