无法访问对象中的对象属性

时间:2018-03-04 22:20:26

标签: reactjs

我似乎无法访问对象中对象的一部分数据。在这里我试图访问配置文件中的喜欢,否则可以使用vanilla javascript打印出这个.state.data.profile.likes

class App extends Component {
     constructor(props) {
        super(props);
        this.state = {
            data: {}
        };
     }

     componentDidMount() {
         var x = {      
             "notifications": 12,
             "profile": {
                 "likes": 5
             }
         };
         this.setState({
             data: x
         });
     }


    render() {
        const {notifications, profile} = this.state;
        return (
            <div>
                <span>Notifications {notifications}</span>
                <span>Likes {profile.likes}</span>
            </div>
        );
}

3 个答案:

答案 0 :(得分:2)

在安装之前 - 以及初始渲染 - 您的状态如下所示:

{
  data: {}
}

安装后 - 在第二次渲染 - 你的状态如下:

{
  data: {
    notifications: 12,
    profile: {
      likes: 5
    }
  }
}

您正试图访问不存在的this.state.profile.likes。大概你的意思是访问确实存在的this.state.data.profile.likes,但仅限于第二次渲染。

答案 1 :(得分:1)

我在尝试解决同一问题的同时注意到了这一点。构造函数应为:

 constructor(props) {
    super(props);
    this.state = {
        data: {
            profile: {}
        }
    };
 }

始终在对象内初始化对象

答案 2 :(得分:0)

https://reactjs.org/docs/react-component.html#mounting

渲染 - &gt; componentDidMount

将状态数据放在构造函数