Uncaught TypeError: Cannot read property 'state' of undefined

后端 未结 3 1960
隐瞒了意图╮
隐瞒了意图╮ 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
    0 讨论(0)
  • 2021-01-29 14:39

    You need to bind this.onSelect If you forget to bind this.onSelect and pass it to onClick, this will be undefined when the function is actually called.

    Try this:

    class SectionAccordion extends React.Component {
    
          constructor(props){
            super(props);
            this.onSelect  = this.onSelect.bind(this);
          }
    
          onSelect() {
    
            this.props._onSelect(this.props.id);
          }
    
          render() {
    
                console.log("accordion / the Accordion Section component");
                var className = 'accordion-section' + (this.props._selected ? ' selected' : '');
    
                return (
                    <div className={className}>
                        <h3 onClick={this.onSelect}>
                            {this.props.title}
                        </h3>
    
                        <div className="up-arrow"></div>
    
    
    
                        <div onClick={this.onSelect} className="body">
                            {this.props.children}
                        </div>
                    </div>
                );
    
          }
    
        }

    Update:

    You can bind the context using arrow function as well ; like this:

    onSelect = () => {
       // code goes here
    }
    
    0 讨论(0)
  • 2021-01-29 14:59

    You need to bind this.

    this.onSelect -> this.onSelect.bind(this)

    this.enhanceSection -> this.enhanceSection.bind(this)

    0 讨论(0)
提交回复
热议问题