未捕获的类型错误:无法读取未定义的属性“状态”

IT技术 javascript html css reactjs redux
2021-05-20 06:35:33

我正在尝试从 React.createClass 更改为 React.Component,但出现以下错误。

Uncaught TypeError: Cannot read property 'state' of undefined 

我用谷歌搜索错误,但无法弄清楚

class Accordion extends React.Component {
3个回答

你需要绑定this

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

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

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

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

extends语法不再自动绑定了像createClass那样。

需要绑定this.onSelect 如果忘记绑定 this.onSelect 并传递给 onClick,则实际调用函数时 this 将是 undefined。

试试这个:

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
}