首页 > 解决方案 > 如何为箭头函数编写替代代码?

问题描述

我目前正在尝试在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
  );
}

但是,然后代码不再起作用。有人能帮助我吗?错误在哪里?

标签: javascriptreactjsarrow-functions

解决方案


那是因为箭头函数不会改变this,而常规函数会。这就是造成你差异的原因。以下是一些选项:

componentDidMount() {
  const that = this;
  this.timerID = setInterval (
    function() {
      that.tick();
    },
    1000
  );
}

或者

componentDidMount() {
  this.timerID = setInterval(this.tick, 1000);
}

推荐阅读