访问嵌套对象

时间:2018-06-26 18:29:54

标签: javascript reactjs

访问嵌套对象中的属性时遇到一些麻烦。我尝试过:

<p>{this.state.post.user.firstName}</p>
<p>{this.state.post.comments[0].user.firstName}</p>

两行都无效,只有<p>{this.state.post.date}</p>有效。

组件:

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

这是我的json的示例:

{ 
 "date": "2018", 
 "user": { "firstName": "Some Name" }, 
 "comments": [
   {
    "body": "here's my comment."
    "user": {
      "firstName": "Some Name", 
      "lastName": "Some Lastname"
     } 
   }, 
   {......}
 ]
}

我得到的错误:

TypeError: Cannot read property 'firstName' of undefined
TypeError: Cannot read property '0' of undefined

1 个答案:

答案 0 :(得分:1)

您很可能会遇到这些错误,因为您没有考虑到post最初是一个空对象,这将导致this.state.post.user.firstNamethis.state.post.comments[0]抛出错误。

您可以改为:

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