如何在React上访问嵌套的JSON数据?

时间:2019-05-28 09:55:40

标签: javascript json api

我无法在Render方法中访问从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对象:

http://dataservice.accuweather.com/forecasts/v1/daily/1day/2094578.json?details=true&apikey=JjaFgoA67A3eXoMR7SiRyprGyPiv4Eln

我收到以下错误:

  

未处理的拒绝(TypeError):无法读取的属性“ ShortPhrase”   未定义的TypeError:无法读取未定义的属性“ ShortPhrase”

但是我应该简短地讲一下天气。

2 个答案:

答案 0 :(得分:0)

返回的数据具有如下结构:

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

答案 1 :(得分:0)

添加如下模板条件: ...

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>

);
}
...