无法读取空反应的 属性 'setState'
Cannot read property 'setState' of null react
这个代码是在回答另一个问题时给我的,它在 Codepen
中工作正常。 Original code
然而,当我尝试将它调整到我的项目时,首先,箭头函数无法识别,我在这个箭头函数处得到了意外的标记错误:
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>
)
}
}
但是现在每当我按下其中一个按钮时,我都会收到错误消息
"Uncaught TypeError: Cannot read property 'setState' of null"
我现在可以做什么来解决这个问题?
谢谢!
实际上this.getBtnId.bind(this)
什么都不做!
这将解决您的问题:
this.getBtnId = this.getBtnId.bind(this);
您的错误来自 getBtnId() 内部。 "this" 关键字在事件处理程序中不可用,除非专门通过它。
实现此目的的标准方法是在将您的函数连接到组件的事件时使用'bind':
<HelpMenu
getBtnId={this.getBtnId.bind(this)}
/>
这个代码是在回答另一个问题时给我的,它在 Codepen
中工作正常。 Original code
然而,当我尝试将它调整到我的项目时,首先,箭头函数无法识别,我在这个箭头函数处得到了意外的标记错误:
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>
)
}
}
但是现在每当我按下其中一个按钮时,我都会收到错误消息
"Uncaught TypeError: Cannot read property 'setState' of null"
我现在可以做什么来解决这个问题?
谢谢!
实际上this.getBtnId.bind(this)
什么都不做!
这将解决您的问题:
this.getBtnId = this.getBtnId.bind(this);
您的错误来自 getBtnId() 内部。 "this" 关键字在事件处理程序中不可用,除非专门通过它。
实现此目的的标准方法是在将您的函数连接到组件的事件时使用'bind':
<HelpMenu
getBtnId={this.getBtnId.bind(this)}
/>