未捕获的TypeError:无法读取未定义的属性“state”

时间:2017-04-27 16:18:37

标签: javascript html css reactjs redux

我正在尝试从React.createClass更改为React.Component,但是我收到了以下错误。

Uncaught TypeError: Cannot read property 'state' of undefined 

我搜索了该错误,但无法弄清楚

class Accordion extends React.Component {

3 个答案:

答案 0 :(得分:2)

您需要绑定this

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

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

答案 1 :(得分:1)

您需要将onSelect绑定到构造函数中的类:

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

extends语法不再像createClass那样具有自动绑定功能。

答案 2 :(得分:1)

你需要绑定this.onSelect  如果您忘记绑定this.onSelect并将其传递给onClick,则在实际调用该函数时,这将是未定义的。

试试这个:

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>
            );

      }

    }

<强>更新

您也可以使用arrow function绑定上下文;像这样:

onSelect = () => {
   // code goes here
}