【发布时间】:2021-02-09 18:02:25
【问题描述】:
我正在启动 React,我发现我可以使用 setInterval() 中的粗箭头函数设置时钟:
class Clock extends React.Component {
constructor(props) {
super(props)
this.state = { date: new Date() }
this.timer = null
}
componentDidMount() {
this.timer = window.setInterval(() => {
this.setState({ date: new Date() })
}, 1000)
}
但是我没有设法通过常规函数获得相同的结果(如下)。我认为它与在常规函数中创建新上下文的“this”关键字相关联?我不知道如何解决这个问题:
componentDidMount() {
this.timer = window.setInterval(function() {
this.setState({ date: new Date() })
}, 1000)
}
感谢您的宝贵时间
【问题讨论】:
标签: javascript reactjs function setinterval arrow-functions