Skip to content

Why is this.state not available by default? #5464

@colllin

Description

@colllin

I'm happy to move this question elsewhere if you can point me in the right direction.

Why do I get an error (Uncaught TypeError: Cannot read property 'someProperty' of null) when I don't call this.setState() before the initial render?

render() {
    return (
        <span>{this.state.someProperty}</span>
    )
}

This error goes away if I simply call this.setState() with an empty object in componentWillMount:

componentWillMount() {
    this.setState({});
}

Isn't this.state part of the core React Component API? Why wouldn't it be present by default?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions