简体   繁体   English

从嵌套的JSON中获取属性

[英]REACT fetch properties from nested JSON

I am using react to render data from properties in a json that is nested . 我正在使用react从嵌套json中的属性渲染数据。 I don't have a problem rendering the properties that are not nested such as 'name' , and 'id' , but when it comes to grabbing a nested prop such as place:location{...} etc, it says "TypeError: Cannot read property 'location' of undefined" 呈现未嵌套的属性(例如'name''id' ,我没有问题,但是在获取嵌套的道具(例如place:location{...}等)时,它会显示"TypeError: Cannot read property 'location' of undefined"

My json format looks as follows: 我的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" }, ...]

This is my react code: 这是我的反应代码:

  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>
     })

  );
 }
}

Any help would be appreciated!!!! 任何帮助,将不胜感激!!!!

It looks like not all events have property place defined. 似乎并非所有events都定义了属性place You can either warn about it on every component or just ignore and prevent undefined values to be rendered: 您可以在每个组件上对其进行警告,也可以忽略并阻止呈现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's get method also can help you with this: Lodash的get方法也可以帮助您:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM