ReactJS中的箭头函数歧义

问题描述 投票:0回答:1
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行的function参数。我认为这是一个箭头功能-我可能错了。我将其替换为常规函数setInterval(function(){this.tick()},1000),并收到一条错误消息,指出tick()不是函数。这里发生了什么事?

reactjs arrow-functions
1个回答
2
投票

this引用在使用旧式function()语法时被重置,而对于=>(箭头功能),this引用被保留。您仍然可以使用function(),但需要调用.bind(this)来“修复” this参考。

所以这个:

this.timerID = setInterval(
    () => this.tick(),
    1000
);

等效于此:

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

您需要这样做,因为setTimeout / setIntervalglobalwindow)对象的成员属性,因此在setTimeoutsetInterval回调中,this引用用于window,而不是呼叫站点的this

© www.soinside.com 2019 - 2024. All rights reserved.