简体   繁体   中英

this.state is undefined inside child component

In my code, I have the render() function. In this method this.state is available. If this.LoadingIcon just contains text, all is good:

public render() {
    return <div>

            <h1>Search company</h1>

            <this.LoadingIcon />

            <label value={this.state.query} />

            <div className='form-group'>
                <input type='text' className='form-control' value={this.state.query} onChange={this.handleChange.bind(this)} />
            </div>

            <button onClick={() => { this.searchVat() }}>Search</button>
        </div>;
}

However, if I suddenly want to use the state and make the LoadingIcon conditional:

LoadingIcon(props: any) {
    if (this.state.loading) {
        return <h1>LOADING</h1>;
    } else {
        return <h1>NOT LOADING</h1>;
    }

}

You get the:

TypeError: Cannot read property 'state' of undefined

Why is this? And how to solve?

There are two issues with your code:

  • this.state is undefined because LoadingIcon is a stateless component
  • in React, the parent's state is not directly available in the child component

To access the parent's state in the child, you need to pass the state as prop:

<this.LoadingIcon loading={this.state.loading} />

Then in your child component, you can use the props to retrieve the parent's state:

LoadingIcon(props: any) {
    if (props.loading) {
        return <h1>LOADING</h1>;
    } else {
        return <h1>NOT LOADING</h1>;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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