REACT从嵌套的JSON中获取属性

时间:2017-10-30 07:06:01

标签: javascript json reactjs api

我正在使用react来呈现 json 嵌套的属性中的数据。我在渲染未嵌套的属性(例如'name''id'时遇到问题,但是当涉及到抓取place:location{...}等嵌套道具时,说"TypeError: Cannot read property 'location' of undefined"

我的json格式如下:

data = [ {
  "end_time": "2015-03-28T21:00:00-0700",
  "name": "Brkn Intl. Bay Area Season 2!",
  "place": {
    "name": "MVMNT Studio",
    "location": {
      "city": "Berkeley",
      "country": "United States",
      "latitude": 37.85381,
      "longitude": -122.27875,
      "state": "CA",
      "street": "2973 Sacramento St",
      "zip": "94702"
    },
    "id": "459771574082879"
  },
  "start_time": "2015-03-28T15:00:00-0700" }, ...]

这是我的反应代码:

  class ResultBox extends Component {
    constructor(props){
    super(props);
    this.state = {
    posts: []
     };
  }
   componentDidMount() {
   axios.get('http://localhost:3001/api/events')
     .then(res => {
     let posts = res.data.map(obj => obj);
     this.setState({posts});
     console.log(posts);
    });

 }
  render() {
   return (
      this.state.posts.map(function(events){
        return <div className='result_box'>

       <p>{events.name}</p>
       <p>{events.place.location.city}</p> <----- This give me error!!!
       </div>
     })

  );
 }
}

任何帮助将不胜感激!!!!

1 个答案:

答案 0 :(得分:3)

看起来并非所有events都定义了属性place。 您可以在每个组件上对其进行警告,也可以忽略并阻止呈现undefined值:

this.state.posts.map(events =>
  <div key={events.id} className='result_box'>
    <p>{events.name}</p>
    {events.place && <p>{events.place.location.city}</p>}
  </div>
)

Lodash的get方法也可以为您提供帮助:

<p>{get(events, 'place.location.city', '')}</p>