Javascript 当我将箭头函数更改为简单函数时,React-JS计时器没有更新?
我一直在玩React的官网上的例子: 我的问题有点棘手: 我有时钟Javascript 当我将箭头函数更改为简单函数时,React-JS计时器没有更新?,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我一直在玩React的官网上的例子: 我的问题有点棘手: 我有时钟组件,它使用 new Date().toLocaleTimeString() 代码:此代码工作正常 import React, { Component } from 'react' import ReactDOM from 'react-dom'; class Clock extends Component { constructor(props) { super(props); this.state =
组件
,它使用
new Date().toLocaleTimeString()
代码:此代码工作正常
import React, { Component } from 'react'
import ReactDOM from 'react-dom';
class Clock extends Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(), //problematic line
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>
)
}
}
function Root() {
const element = <Clock />
ReactDOM.render(
element,
document.getElementById('root')
);
}
export default Root;
import React,{Component}来自“React”
从“react dom”导入react dom;
类时钟扩展组件{
建造师(道具){
超级(道具);
this.state={date:new date()};
}
componentDidMount(){
this.timerID=setInterval(
()=>this.tick(),//有问题的行
1000
);
}
组件将卸载(){
clearInterval(this.timerID);
}
勾选(){
这是我的国家({
日期:新日期()
});
}
render(){
返回(
你好,世界!
它是{this.state.date.toLocaleTimeString()}。
)
}
}
函数根(){
常量元素=
ReactDOM.render(
元素,
document.getElementById('root'))
);
}
导出默认根目录;
问题
但问题是,当我将()=>this.tick()
更改为this.tick()
或this.tick
时,计时器只会第一次运行,不会连续运行。在这种情况下,我非常困惑:
任何人都能告诉我,在这种情况下,()=>this.tick()
和this.tick()
之间有什么区别,或者为什么当我将这个()=>this.tick()
更改为this.tick()
时,计时器没有更新
const object1 = {
method(){
setTimeout(function () { console.log(this) })
}
}
const object2 = {
method(){
setTimeout(() => { console.log(this) })
}
}
// the same as
var object3 = {
method: function method() {
var _this = this;
setTimeout(function() {
console.log(_this);
});
}
};
object1.method(); // window
object2.method(); // object2
object3.method(); // object3
影响本规范运行的唯一区别是
()=>this.tick()
是一个函数,其中
this.tick()
是一个函数调用语句
因此,set timer的第一个参数应该是在时间间隔之后调用的函数。当您将其更改为this.tick()时,setTimeout将尝试执行此.tick(),但该操作将不起作用。这在setTimeout函数第一次初始化时起作用。调用参数(函数)而不是初始化参数。如果查找函数setInterval,您会注意到第一个参数(firstArg)必须是返回另一个函数和第二个参数(secondArg)的函数必须是一个数字或数字数组,表示要重复作为第一个参数给定的函数的延迟
setInterval(firstArg, secondArg) // typeof firstArg must be a function that returns something
在您的情况下,只需传递不返回任何内容的“this.tick()”或“this.tick”。由于this.tick()不返回任何内容,因此setInterval无法继续更新“date”状态
如果将勾选()改为
或
你可以做到这一点
componentDidMount() {
this.timerID = setInterval(
this.tick()
1000
);
}
但是如果我将()=>this.tick()转换为this.tick,那么它也不起作用,那么这背后的原因是什么,因为this.tick是对函数的引用?我说的对吗?你的回答很好,这有助于我清楚地理解这个概念。谢谢。很高兴我的回答能帮助你:)
tick = () => () => {
this.setState({
date: new Date()
});
}
componentDidMount() {
this.timerID = setInterval(
this.tick()
1000
);
}