Uncaught TypeError: Cannot read property 'state' of undefined

后端 未结 3 1987
隐瞒了意图╮
隐瞒了意图╮ 2021-01-29 14:04

I am trying to change from React.createClass to React.Component, but I am getting below error.

Uncaught TypeError: Cannot read property \'state\' of undefined 
<         


        
3条回答
  •  日久生厌
    2021-01-29 14:36

    You need to bind your onSelect to the class in the constructor:

    constructor(props) {
        super(props);
        this.state = {
            selected: props.selected // use props, not this.props
        };
        this.onSelect = this.onSelect.bind(this);
    }
    

    The extends syntax no longer has autobinding like createClass did.

    • http://reactkungfu.com/2015/07/why-and-how-to-bind-methods-in-your-react-component-classes/
    • https://facebook.github.io/react/docs/handling-events.html

提交回复
热议问题