繁体   English   中英

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

[英]React this.state is undefined in component function

函数typeContactGetter绑定到此并且一切正常,唯一的问题是在<li>元素的函数返回中,我试图设置一个来自state的className并且它返回this.state undefined。

为什么会这样?

谢谢,巴德

零件

class ContactType extends Component {

    constructor(props) {
        super(props);
        this.state = {
            date: new Date(),
            hiddenList: false,
            familyContacts: this.typeContactGetter("Family"),
            friendContacts: this.typeContactGetter("Friends")
        };
        this.typeContactGetter = this.typeContactGetter.bind(this);
        this.handleClick = this.handleClick.bind(this);
        this.hideList = this.hideList.bind(this);
    }

    handleClick = (event) => {
        event.preventDefault();
        console.log('clicked, state: ' + this.state.hiddenList);
    };

    hideList = () => {
        console.log("this is hidelist: " + this.state.hiddenList);
        if (this.state.hiddenList === true){
            this.setState({
                hiddenList: false
            });
        }
        this.setState({
            hiddenList: !this.state.hiddenList
        });
    };

    typeContactGetter = (name) => {
        console.log(this.state);
        for (let contact of CONTACTS) {
            if (contact.name === name) {
                return (
                    <li  className={this.state.hiddenList ? 'hidden' : ''} onClick={this.handleClick} key={contact.id.toString()}>
                        {contact.contacts.map(value => {
                            if (value.type === "Contact") {
                                return (
                                    <a key={value.id.toString()} href="#">{value.name}</a>
                                );
                            }
                        })
                        }
                    </li>
                );
            }
        }
    };
    render() {
        return (
            <ContactView familyContacts={this.state.familyContacts} friendContacts={this.state.friendContacts} hideList={this.hideList}/>
        );
    }
}

export default ContactType;

那是因为你在实际创建状态之前在构造函数中调用了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}/>

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM