javascript - Accessing nested object
问题描述
I'm having some trouble accessing the properties in the nested object. I've tried:
<p>{this.state.post.user.firstName}</p>
<p>{this.state.post.comments[0].user.firstName}</p>
Both lines don't not work, only <p>{this.state.post.date}</p>
works.
Component:
state = {
post: {}
}
async componentDidMount() {
const { post_id } = this.props.match.params;
const response = await axios.get(`/posts/${post_id}`);
this.setState({
post: response.data
})
}
render() { return( ...... )}
Here's an example of my json:
{
"date": "2018",
"user": { "firstName": "Some Name" },
"comments": [
{
"body": "here's my comment."
"user": {
"firstName": "Some Name",
"lastName": "Some Lastname"
}
},
{......}
]
}
The error I'm getting:
TypeError: Cannot read property 'firstName' of undefined
TypeError: Cannot read property '0' of undefined
解决方案
You are most likely getting these errors because you are not taking into consideration that post
is initially an empty object, which will cause this.state.post.user.firstName
and this.state.post.comments[0]
to throw an error.
You could do this instead:
class MyComponent extends React.Component {
state = {
post: null
}
async componentDidMount() {
const { post_id } = this.props.match.params;
const response = await axios.get(`/posts/${post_id}`);
this.setState({
post: response.data
});
}
render() {
const { post } = this.state;
return post ? (
<div>
<p>{post.user.firstName}</p>
<p>{post.comments[0].user.firstName}</p>
<p>{post.date}</p>
</div>
) : null;
}
}
推荐阅读
- php - 使用 Jetstream 在 Laravel 8 中添加新 Livewire 组件时如何解决 RootTagMissingFromViewException 错误
- r - 在 R 中选择某些标签
- visual-c++ - MSVC++ 和 SSE2
- javascript - d3 元素未在反应中显示
- r - 如何在 Rstudio 中组合两个时间序列?
- r - 从R中没有列名的行返回所有值
- javascript - 如何仅从组件中动态导入 JS 并仍然拆分其资产?
- python - 生成器模型仅生成黑色图像。在神经网络中找不到问题
- c++ - 如何在 Qt C++ 中管理来自另一个窗口的窗口元素
- if-statement - NetLogo IF 语句颜色变化