reactjs - ReactJS 中的箭头函数歧义
问题描述
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
在上面的代码中 - 我无法理解 setInterval() 行 - 准确地说是 setInterval 行的函数参数。我认为这是一个箭头函数——我可能错了。我将其替换为常规函数setInterval(function(){this.tick()},1000)
,并收到错误提示 tick() 不是函数。这里发生了什么事?
解决方案
使用this
旧式function()
语法时会重置引用,而使用=>
(arrow-functions)this
会保留引用。您仍然可以使用function()
,但您需要调用.bind(this)
以“修复”this
引用。
所以这:
this.timerID = setInterval(
() => this.tick(),
1000
);
相当于这个:
this.timerID = setInterval(
function() { this.tick(); }.bind(this),
1000
);
您需要这样做,因为setTimeout
/setInterval
是global
( window
) 对象的成员属性,因此在 asetTimeout
或setInterval
回调中this
引用是 for window
,而不是调用站点的this
。
推荐阅读
- .net-core - 当我添加相关实体时,实体状态被修改未添加
- r - 如何旋转 tf$keras$preprocessing$image$apply_affine_transform 的边界框
- javascript - 非导出函数的 Mocha 单元测试返回“xx 不是函数”
- arrays - Sending a concatenated bytearray
- python - 当所有方法都返回 NotImplemented 时,为什么 == 不引发“不支持 TypeError”?
- django - Redis 服务器未在 Windows 10 上启动
- java - 如何防止 Spring Data JPA 中的自动更新?
- directx-11 - D3D11 - 如何在没有 Windows 10 的情况下在显示器上启用 HDR
- html - 如何使用物化 CSS 使表单在从应用程序打开时响应手机
- xcode - SwiftUI ScrollView 总是没有 ResponsiveScrolling