React中的JSON数据对象处理



无法了解如何从解析并存储的json对象中提取数据。。。我尝试了很多方法,但都出现了错误(数据来自openweathermap(

class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
data: null
};
}
getWeather(url) {
fetch(url)
.then(res => res.json())
.then(data =>
this.setState({
isLoading: false,
data: data
})
)
.catch(error => console.log("Error Loading data " + error));
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(position => {
const url = `${API}lat=${position.coords.latitude}&lon=${position.coords.longitude}&${APPID}`;
this.getWeather(url);
});
}
render() {
return (
<div>
{console.log(this.state.data)}
{/*renders json*/}
<h1>{this.state.data.name}</h1>
</div>
);
}
}

我相信您可能会得到cannot read property 'name' of null。不确定确切的错误,但大概是这样。

尝试使用

<h1>{ this.state.data && this.state.data.name }</h1>

在API未给出响应之前,您的状态数据为null,因此无法访问data.name

最新更新