【发布时间】:2020-06-05 18:49:15
【问题描述】:
这个问题看起来很简单,但我不知道如何解决它:
- 在
render-Function 中声明的添加按钮可以正常工作 - 在
state中声明的添加按钮本身不起作用。正如代码已经提到的,它会抛出"TypeError: Cannot read property 'state' of undefined"-Error
class App extends Component {
constructor() {
super();
this.state = {
someArrayOfObjects: [{
attr:
// SNIP ...
// Doesn't work!
// When clicked leads to this error: "TypeError: Cannot read property 'state' of undefined"
<button onClick={this.doAction}>Add</button>
// SNIP ...
}]
};
this.doAction = this.doAction.bind(this);
}
// SNIP ...
doAction() {
console.log(this.state);
}
render() {
return(
// SNIP...
// Works just fine
<button onClick={this.doAction}>Add</button>
)
}
}
我错过了什么?
【问题讨论】:
-
尝试使用箭头函数
<button onClick={() => this.doAction}>Add</button> -
如果要绑定doAction,请在将其传递给状态声明中的组件之前执行此操作。否则,调用该函数时 this 将是未定义的。
-
@Sam 谢谢,但箭头功能不起作用
标签: javascript reactjs react-state-management