在组件函数中未定义React this.state

时间:2018-04-06 17:00:59

标签: reactjs ecmascript-6

函数syntax error in field definition 绑定到此并且一切正常,唯一的问题是在typeContactGetter元素的函数返回中,我试图设置一个来自状态的className并返回undefined for <li>

为什么会这样?

谢谢, 芽

成分

this.state

1 个答案:

答案 0 :(得分:3)

那是因为你在实际创建状态之前在构造函数中调用typeContactGetter

constructor(props) {
    super(props);
    this.state = {
        date: new Date(),
        hiddenList: false,
        familyContacts: this.typeContactGetter("Family"), // hey, but we are actually creating the state right now
        friendContacts: this.typeContactGetter("Friends")
    };
}

为什么要将组件列表保留在状态中?也许最好直接传递它们:

constructor(props) {
    super(props);
    this.state = {
        date: new Date(),
        hiddenList: false,
    };
}

....

<ContactView familyContacts={this.typeContactGetter("Family")} friendContacts={this.typeContactGetter("Friends")} hideList={this.hideList}/>

顺便说一句,你不需要绑定函数,因为它们已经被箭头函数绑定了。

相关问题