首页 > 解决方案 > 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

标签: javascriptreactjs

解决方案


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

推荐阅读