reactjs - 无法更新状态,出现“未定义”错误
问题描述
我正在尝试更新我的罢工,但是当我这样做时,出现错误
无法读取未定义的属性“罢工”
我的代码有什么错误?有人帮我弄清楚吗?
这是我的课:
无法读取未定义的属性“罢工”
class LightningCounter extends React.Component {
constructor(props) {
super(props);
this.state = {
strikes: 0
};
}
timerTick() {
this.setState({
strikes: this.state.strikes + 100 //getting red underline here
});
}
componentDidMount() {
setInterval(this.timerTick, 1000);
}
render() {
return <h1>{this.state.strikes}</h1>;
}
}
解决方案
那是因为 this 关键字的上下文,this 计时器不知道它属于类,它指向自己作为函数。
现在像这样使用作为 ES6 标准的箭头函数
timerTick = () => {
`enter code here`
}
或在构造函数中以这种方式绑定函数
this.timerTick = this.timerTick.bind(this);
检查 bind 的文档以获得更清晰的信息
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind
希望它有效
推荐阅读
- javascript - 在 Slate.js editor.apply(operation) 中没有正确应用“split_node”操作
- python - 变量选择涉及数字、高基数、低基数特征的混合
- javascript - 如何将数据传递给 props.children?
- flutter - 如何编写当且仅检测到更改时运行的颤振函数?
- python-3.x - 如何执行刚刚安装的最新版本的python?
- java - JavaFX StringProperty.isEmpty
- c# - 如何更新数据表中的特定列?
- python - Tensorflow 2:序列化和解码时的形状不匹配
- soap - 如何在生成的 wsdl 中指定模式位置
- reactjs - 在基于类的组件中使用调度会导致无效的钩子调用错误