【问题标题】:Cannot read property 'setState' of null react无法读取 null 反应的属性“setState”
【发布时间】:2017-02-21 09:43:11
【问题描述】:

此代码是在回答另一个问题时给我的,它在Codepen 中运行良好。 Original code

但是,当我尝试将其调整到我的项目时,首先,箭头函数无法识别,并且在此箭头函数处出现 Unexpected token 错误:

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

于是我把它改成了普通函数,现在组件看起来是这样的:

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

}

但是现在每当我按下其中一个按钮时都会出现错误

“未捕获的类型错误:无法读取 null 的属性 'setState'”

我现在可以做些什么来解决这个问题?

谢谢!

【问题讨论】:

    标签: javascript reactjs single-page-application typeerror arrow-functions


    【解决方案1】:

    其实this.getBtnId.bind(this)什么都不做!

    这将解决您的问题:

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

    【讨论】:

      【解决方案2】:

      您的错误来自 getBtnId() 内部。 “this”关键字在事件处理程序中不可用,除非专门通过它。

      实现这一点的标准方法是在将函数连接到组件的事件时使用“绑定”:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-16
        • 1970-01-01
        • 1970-01-01
        • 2017-09-24
        • 2021-11-21
        • 2018-10-06
        • 2020-09-07
        • 2017-01-01
        相关资源
        最近更新 更多