javascript - 按钮单击时无法读取 null 的属性“setState”
问题描述
我正在开发一个 reactjs 应用程序,并且在访问 updateVert 函数中的状态时遇到了这个问题。当我单击“播放”按钮时,会调用 actionButton 并从 actionButton 内部调用 updateVert。
下面是我的代码片段
updateVert() {
console.log("inside upver")
if(play) {
cancelAnimationFrame(this.updateVert);
return;
}
this.setState({xPos: this.state.xPos + 1}, ()=>{
if(this.state.xPos >= w) {
// stop animation...
this.setState({xPos:0, playing:false});
}
ctx.clearRect(0, 0, w, h);
// draw new one...
ctx.beginPath();
ctx.strokeStyle = "#19f";
ctx.lineWidth = 2;
ctx.moveTo(this.state.xPos, 0);
ctx.lineTo(this.state.xPos, 200);
ctx.stroke();
if(this.state.playing) {
console.log("yes true")
requestAnimationFrame(this.updateVert)
};
})
// reset rectangle content to erase previous line...
}
actionButton(){
if(this.state.playing) {
// pause...
this.setState({playing:false},()=>{
console.log(this.state.playing)
})
}
else {
this.setState({playing:!this.state.playing},()=>{
console.log(this.state.playing)
this.updateVert();
})
}
}
render() {
return (
<div>
<div className="App">
<canvas id="DemoCanvas" width="500" height="200"></canvas>
</div>
<button onClick={this.actionButton.bind(this)}>{this.state.playing ? "Stop":"Play"}</button>
</div>
);
}
当我单击按钮(播放/暂停)时,我收到错误消息
TypeError: Cannot read property 'setState' of null
updateVert
src/App.js:45
42 | return;
43 | }
44 |
> 45 | this.setState({xPos: this.state.xPos + 1}, ()=>{
46 | if(this.state.xPos >= w) {
47 | // stop animation...
48 | this.setState({xPos:0, playing:false});
我已经正确引用了 updateVert 函数。我究竟做错了什么?
解决方案
您缺少绑定上下文this
:
在actionButton(){
您调用的钩子this.updateVert()
中,没有绑定this
. 因此将其绑定在构造函数中:
this.updateVert.bind(this)
推荐阅读
- apache - 使用 SSL 为子域设置 .access
- point-cloud-library - 带有 pcl 的 IterativeClosestPoint 没有给出预期的结果
- r - 每个过滤后的数据集具有不同颜色的散点图
- html - 作为电子邮件模板发送时,图像路径被打乱
- c# - 如何在 C# 中获取数字角色 OnEnroll 事件
- html - 背景图片没有填满整个页面
- swift - 如何在 SwiftUI 中从一个视图重定向到另一个视图?
- node.js - 如何从反应提交多部分/表单数据到表达?
- android - Android Studio 未安装在混音操作系统模拟器上
- html - 如何在角度禁用和启用按钮