首页 > 解决方案 > 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() 不是函数。这里发生了什么事?

标签: reactjsarrow-functions

解决方案


使用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/setIntervalglobal( window) 对象的成员属性,因此在 asetTimeoutsetInterval回调中this引用是 for window,而不是调用站点的this


推荐阅读