Uncaught TypeError: Cannot read property 'stat

2019-03-07 04:37发布

问题:

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 

I googled for the error but an not able to figure it out

class Accordion extends React.Component {

回答1:

You need to bind this.

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

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



回答2:

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


回答3:

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
}