React:在状态中引用函数时出错
React: Error referencing a function within state
问题看似简单,但我想不出如何解决:
- 在
render
函数中声明的添加按钮工作正常
- 在
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>
)
}
}
我错过了什么?
您需要在 state
之前绑定函数 doAction
constructor() {
super();
this.doAction = this.doAction.bind(this);
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
引用组件的原型方法 class。但是你 can't pass a method as a callback directly, so you need to bind it. Function.prototype.bind
creates a new function,然后将其分配给在构造函数中创建的实例:
this.doAction = this.doAction.bind(this);
因此,可能令人困惑的是,this.doAction
指的是代码中不同位置的两个 不同 函数。您想要将绑定版本传递给处理程序(请参阅上面的 link 了解原因),因此您需要在创建该按钮之前绑定它。
请检查沙箱中的代码:
https://codesandbox.io/s/young-architecture-0r1tk
在这里你可以看到我们需要在将方法添加到状态之前定义方法。
首先我们需要定义 doAction
方法,然后定义状态,因为它在状态内部使用。
问题看似简单,但我想不出如何解决:
- 在
render
函数中声明的添加按钮工作正常 - 在
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>
)
}
}
我错过了什么?
您需要在 state
doAction
constructor() {
super();
this.doAction = this.doAction.bind(this);
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
引用组件的原型方法 class。但是你 can't pass a method as a callback directly, so you need to bind it. Function.prototype.bind
creates a new function,然后将其分配给在构造函数中创建的实例:
this.doAction = this.doAction.bind(this);
因此,可能令人困惑的是,this.doAction
指的是代码中不同位置的两个 不同 函数。您想要将绑定版本传递给处理程序(请参阅上面的 link 了解原因),因此您需要在创建该按钮之前绑定它。
请检查沙箱中的代码: https://codesandbox.io/s/young-architecture-0r1tk
在这里你可以看到我们需要在将方法添加到状态之前定义方法。
首先我们需要定义 doAction
方法,然后定义状态,因为它在状态内部使用。