【问题标题】:Uncaught TypeError: Cannot read property 'state' of undefined未捕获的类型错误:无法读取未定义的属性“状态”
【发布时间】:2017-04-27 16:18:37
【问题描述】:

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

Uncaught TypeError: Cannot read property 'state' of undefined 

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

class Accordion extends React.Component {

【问题讨论】:

    标签: javascript html css reactjs redux


    【解决方案1】:

    你需要绑定this

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

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

    【讨论】:

    • 嘿,那个已经修好了,但我在这里遇到了孩子未定义的错误 id = child.props.id;
    • 你能说出原因有助于理解吗
    【解决方案2】:

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

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

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

    【讨论】:

    • 嘿,那个已经修好了,但我在这里遇到了孩子未定义的错误 id = child.props.id;
    • @im 你能说出它有助于理解的原因吗
    【解决方案3】:

    你需要绑定this.onSelect 如果忘记绑定 this.onSelect 并传递给 onClick,则在实际调用函数时 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>
                );
    
          }
    
        }

    更新:

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

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

    【讨论】:

    • 嘿,那个已经修好了,但我在这里遇到了孩子未定义的错误 id = child.props.id;
    • 你能说出原因有助于理解吗
    • JavaScript, class 方法默认不绑定。如果您忘记 bind this.onSelect 并将其传递给 onClick,则在实际调用 function 时,这将是 undefined。这不是 React 特定的行为,它是函数在 JavaScript 中工作方式的一部分。一般来说,如果你引用的方法后面没有(),比如onClick={this. onSelect},你应该bind那个方法..
    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 2023-03-21
    • 2020-05-16
    • 2017-01-23
    • 2021-12-22
    • 2015-01-06
    • 2017-07-26
    相关资源
    最近更新 更多