javascript - 如何为箭头函数编写替代代码?
问题描述
我目前正在尝试在https://en.reactjs.org/docs/state-and-lifecycle.html上做 React 教程。在代码中有以下带有箭头功能的块。
https://codepen.io/gaearon/pen/zKRqNB?editors=0010
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
作为一个初学者,我对箭头函数的经验很少,不太明白什么时候使用它们才有意义,所以我想把它写成一个普通的函数。所以我改变了我的代码如下:
componentDidMount() {
this.timerID = setInterval (
function() {
this.tick();
},
1000
);
}
但是,然后代码不再起作用。有人能帮助我吗?错误在哪里?
解决方案
那是因为箭头函数不会改变this
,而常规函数会。这就是造成你差异的原因。以下是一些选项:
componentDidMount() {
const that = this;
this.timerID = setInterval (
function() {
that.tick();
},
1000
);
}
或者
componentDidMount() {
this.timerID = setInterval(this.tick, 1000);
}
推荐阅读
- javascript - `yarn add` 和 `npm install --save` 都不会将包安装到本地项目
- javascript - Firebase SDK 身份验证 reauthenticateWithCredential 有什么意义?
- spring-boot - 弹簧配置文件未加载某些属性?
- ios - 为什么通知服务扩展没有在 iOS 14 上触发?
- scala - 将 Scala 3.0 SDK 添加到 IntelliJ
- python - 在 python 中使用 pymodbus 读取离散输入
- ios - iOS - 仅使用 Opus 编解码器的 WebRTC 单向音频
- python - 在给定系数列表的情况下计算互补 CDF
- sql - 数据工厂复制数据mssql到postgresql十进制数值数据转换错误
- quickfix - QuickFixN:如何在 QuoteRequest 消息上按特定顺序设置字段?