gpt4 book ai didi

javascript - REACT 从嵌套 JSON 中获取属性

转载 作者:行者123 更新时间:2023-11-28 17:44:47 25 4
gpt4 key购买 nike

我正在使用 React 来渲染 json 中嵌套的属性中的数据。我在渲染非嵌套属性(例如 'name''id')时没有问题,但是当涉及到获取嵌套属性(例如place:location{...} 等,它显示 “TypeError: 无法读取未定义的属性‘位置’”

我的 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" }, ...]

这是我的 react 代码:

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

);
}
}

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

最佳答案

看起来并非所有事件都定义了属性place。您可以在每个组件上发出警告,也可以忽略并阻止呈现未定义的值:

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

洛达什的get方法也可以帮助你:

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

关于javascript - REACT 从嵌套 JSON 中获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47009688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com