javascript - 反应 setTimeout 钩子 onclick
问题描述
当我单击下一个按钮时,它给出了一个错误无法读取未定义的属性“handleCheck”。任何人都可以帮忙吗?在此先感谢
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
state = { check: false };
handleCheck = () => {
console.log("hello");
this.setState({ check: !this.state.check });
};
componentDidMount() {
setTimeout(() => {
this.handleCheck();
}, 10000);
}
timer() {
setTimeout(() => {
this.handleCheck();
}, 10000);
}
render() {
return (
<div>
<p>hello</p>
{this.state.check ? (
<button onClick={this.timer}>Next</button>
) : (
<div>button not showing </div>
)}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("container"));
解决方案
timer
也应该是一个箭头函数来引用正确的this
:
timer = () => {
setTimeout(() => {
this.handleCheck();
}, 10000);
}
解决此问题的另一种方法是绑定this
到timer
.
而且由于新状态依赖于旧状态,所以handleCheck
函数应该是这样的:
handleCheck = () => {
console.log("hello");
this.setState(prevState => ({ check: !prevState.check }));
};
推荐阅读
- python - 在python的单行循环内添加多个条件
- r - 连接字符串中的自定义因子级别
- bootstrap-4 - Flexbox 不能正常工作(当我点击 M 屏幕尺寸时不要转动)
- python - str.translate 方法没有替代
- nsis - 如何使用 NSIS 在 Windows 安装程序完成页面中设置默认选中的复选框
- python - 在 h5py 中什么是类型“|V15060”
- python - 如何使用 Chalice 和 Boto3 显示项目 dynamodb
- c++ - 如何在 Eigen 中禁用并行化
- java - 贪吃蛇游戏:画身体
- react-native - v3 中 React 导航底部选项卡栏的图标不显示