[英]How do you access nested JSON data on React?
我在渲染方法中訪問React上從Accuweather API獲取的JSON數據時遇到問題。
我在React上執行此操作並獲取未定義的錯誤,即使我在打開鏈接並格式化時在JSON視圖中看到了該值。 我嘗試過使用點法,但沒有運氣。
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {
items:[],
isLoaded: false,
}
}
componentDidMount() {
fetch('http://dataservice.accuweather.com/forecasts/v1/daily/1day/2094578.json?details=true&apikey=JjaFgoA67A3eXoMR7SiRyprGyPiv4Eln')
.then(res => res.json())
.then(json => {
this.setState({
isLoaded:true,
items:json,
})
})
}
render() {
var {isLoaded, items} = this.state;
if (!isLoaded) {
return <div> Loading...</div>;
}
else {
return (
<div className="App">
<h1>IES Storm Water Forecast</h1>
<h1>{new Date().toString()}</h1>
<h2> Weather Forcast: {items["DailyForecasts"]["Day"]["ShortPhrase"]}</h2>
<h3>Description: {items.Headline.Text}</h3>
<h6>Source: Accuweather</h6>
</div>
);
}
}
}
export default App;
那里的JSON對象:
我收到以下錯誤:
未處理的拒絕(TypeError):無法讀取未定義的TypeError屬性'ShortPhrase':無法讀取未定義的屬性'ShortPhrase'
但我應該對天氣做一個簡短的判決。
返回的數據有如下結構:
obj = {
DailyForecasts: [
{
Day: {
Icon: 6,
IconPhrase: "Mostly cloudy",
ShortPhrase: "Mostly cloudy",
LongPhrase: "Mostly cloudy"
}
}
]
};
您可以看到DailyForecasts返回一個數組 。 在訪問其中的對象之前,您必須訪問此數組:
items["DailyForecasts"][0]["Day"]["ShortPhrase"]
或者用較短的點符號表示:
items.DailyForecasts[0].Day.ShortPhrase
添加如下模板條件:...
else {
return (
<div className="App">
<h1>IES Storm Water Forecast</h1>
<h1>{new Date().toString()}</h1>
<h2> Weather Forcast: {items["DailyForecasts"]["Day"] && items["DailyForecasts"]["Day"]["ShortPhrase"]}</h2>
^^^
<h3>Description: {items.Headline.Text}</h3>
<h6>Source: Accuweather</h6>
</div>
);
}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.