简体   繁体   English

无法读取null的属性“ setState”

[英]Cannot read property 'setState' of null react

This code was given to me while answering another question, it works fine in Codepen . 该代码是我在回答另一个问题时提供的,在Codepen可以正常工作。 Original code 原始码

However when I try adapting it to my project, first of all, the arrow function is not recognized and I get the Unexpected token error at this arrow function: 但是,当我尝试使其适应我的项目时,首先,无法识别箭头功能,并且在此箭头功能处出现意外令牌错误:

getBtnId = (e) => {
    //code in here
};

So I changed it to a regular function, and now the component looks like this: 所以我将其更改为常规函数,现在该组件如下所示:

export default class HelpPage extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        panelIndex: 0
    };
    this.getBtnId.bind(this);
}

getBtnId (e) {
    if(e.target && e.target.nodeName == "BUTTON") {
        console.log(e.target);
        this.setState({
            panelIndex: Number(e.target.id)
        });
  }
  return e;
};

render() {
    return (
        <div className="container">
            <HelpMenu
                getBtnId={this.getBtnId}
            />
            <HelpPanels
                panelIndex={this.state.panelIndex}
            />
        </div>
    )
}

} }

However now whenever I press one of the buttons I get the error 但是现在每当我按下按钮之一时,我都会收到错误消息

"Uncaught TypeError: Cannot read property 'setState' of null" “未捕获的TypeError:无法读取null的属性'setState'

What can I do now to fix this? 我现在该怎么做才能解决此问题?

Thanks! 谢谢!

Actually this.getBtnId.bind(this) do nothing ! 实际上this.getBtnId.bind(this)什么都不做!

This will solve your problem : 这将解决您的问题:

this.getBtnId = this.getBtnId.bind(this);

Your error is coming from inside getBtnId(). 您的错误来自getBtnId()内部。 The "this" keyword is not available inside event handlers without specifically passing it through. 如果未明确传递,则“ this”关键字在事件处理程序中不可用。

The standard way to achieve this is to use 'bind' when connecting your function to the component's event: 实现此目的的标准方法是在将函数连接到组件的事件时使用“绑定”:

<HelpMenu
  getBtnId={this.getBtnId.bind(this)}
/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM