Uncaught TypeError: Cannot read property 'stat

2019-03-07 04:21发布

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 {

3条回答
Anthone
2楼-- · 2019-03-07 05:05

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
}
查看更多
趁早两清
3楼-- · 2019-03-07 05:12

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.

查看更多
对你真心纯属浪费
4楼-- · 2019-03-07 05:18

You need to bind this.

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

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

查看更多
登录 后发表回答