如何访问json数组中的嵌套对象属性

时间:2018-05-30 13:57:53

标签: reactjs

大家好我试图使用天气地下天文学api,但我得到一个错误,说对象无效作为React孩子(找到:带有键的对象{percentIlluminated,ageOfMoon,phaseofMoon,hemisphere,current_time。
如果您要渲染子集合,请改用数组。

这是json,如何在没有gettig这个错误的情况下访问moon_phase和sun_phase中的属性?任何帮助是极大的赞赏!

    {
    "response": {
    "version": "0.1",
    "termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
    "features": {
    "astronomy": 1
    }
    },
    "moon_phase": {
    "percentIlluminated": "99",
    "ageOfMoon": "16",
    "phaseofMoon": "Full",
    "hemisphere": "North",
    "current_time": {
    "hour": "7",
    "minute": "27"
    },
    "sunrise": {
    "hour": "5",
    "minute": "44"
    },
    "sunset": {
    "hour": "20",
    "minute": "17"
    },
    "moonrise": {
    "hour": "21",
    "minute": "22"
    },
    "moonset": {
    "hour": "6",
    "minute": "45"
    }
    },
    "sun_phase": {
    "sunrise": {
    "hour": "5",
    "minute": "44"
    },
    "sunset": {
    "hour": "20",
    "minute": "17"
    }
    }
    }

App.js

getTrail = async (e) => {
    e.preventDefault();


    const city = e.target.city2.value;


    const country = e.target.country.value;


    const api_call = await fetch(`https://api.wunderground.com/api/b1049a092a7f69ea/astronomy/q/${country}/${city}.json`);

    const data = await api_call.json();

   if (city) {
      this.setState({
        moon_phase: data.moon_phase,
        sunset: data.sunset

      });
    } else {
      this.setState({
         moon_phase: undefined,
        sunset: undefined
      });
    }
  }








    render() {
        return (
          <div>

          <div className="container">
        <div className="row">
          <div id="city">

                  <div>
    <Form getTrail={this.getTrail} />

  <div className="row">
        <div className="col-md-6 offset-md-3">
          <div className="card">
            <div className="card-block">
              <h4 className="card-title">{this.state.moon_phase}</h4>
              <h4 className="card-title">{this.state.sunset}</h4>

 </div>
 </div>
 </div>

1 个答案:

答案 0 :(得分:0)

尝试JSON.stringify(this.state.moon_phase)和JSON.stringify(this.state.sunset)返回一个字符串,而不是一个Object