簡體   English   中英

setInterval function 無箭頭 function

[英]setInterval function without arrow function

我正在學習文檔https://facebook.github.io/react/docs/state-and-lifecycle.html之后的反應組件

為什么我們需要在這里使用箭頭 function:

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

為什么我不能只說(顯然它不起作用)

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

setInterval的第一個參數是function類型。 如果你這樣寫:

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

...然后你不傳遞函數,而是立即執行函數this.tick然后傳遞該函數調用返回的值作為參數。

可以這樣寫:

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

如果省略括號,則傳遞對this.tick函數的引用,然后在 1000 毫秒后由setInterval執行。

setInterval將函數作為第一個參數,在第二種情況下它獲取返回值

將其更改為

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

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

當您想將函數綁定到 React 上下文時,這可能是您所需要的。

請參閱有關為什么需要在 React 中綁定函數的答案

如果你不這樣做,你可以簡單地寫

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

為什么這里需要使用箭頭函數

答案很簡單:查看實時腳本示例中的結果...

 class Persons{ scopeOne(){ // your will see the result this will display our current object 'Persons' setInterval(function(){ console.info(' SCOPE ONEo : '+this); },3000); } scopeTwo(){ setInterval(function(){ console.info(' SCOPE TWO : '+this); }.bind(this) ,3000); } scopeThree(){ setInterval(() => { console.info(' SCOPE THREE : '+this) },3000); } } let p = new Persons(); p.scopeOne(); p.scopeTwo(); p.scopeThree();

在第一個范圍中,結果是WINDOW OBJECT,因此我們無法訪問我們當前的類范圍,因此在第二個范圍中,我們將范圍與 bind(this) 一起使用,這有助於綁定我們當前的對象范圍,在第三個范圍中,它與調用當前對象的第二個范圍相同....

將名為 Tick 的 function 轉換為具有匿名 function 的變量,因此您可以將其作為不帶括號的參數傳遞。

以此代碼( https://codepen.io/gaearon/pen/amqdNr?editors=0010 )為基礎,您可以像這樣更新:

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

  tick = () => {
    this.setState({
      date: new Date()
    });
  }

您需要提供一個函數引用,您正在嘗試調用一個函數,除非該函數返回一個函數引用,否則您的代碼將無法工作

它應該看起來像這樣

this.tick = function() { .... }

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

如果您沒有使用箭頭函數,那么您的代碼應該如下所示:

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

對此的簡單回答是,tick 函數需要能夠訪問其 use/ this的上下文,也就是 Clock 組件。 換句話說,它需要綁定到 Clock 組件,以便它在 Clock 組件的上下文中工作,而不是在 Clock 組件之外的全局上下文中工作。

React 類中的函數默認不綁定,綁定失敗將返回undefined而不是預期的結果。

有幾種方法可以將滴答函數綁定到 Reactjs 網站上的 Clock 組件示例。

  1. 箭頭函數可以訪問this ,這就是在示例中使用它們的原因。 換句話說,隱式編寫箭頭函數意味着它將其內容綁定到本地上下文(在本例中為 Clock 組件)。 在這篇Medium 文章中閱讀更多相關內容

  2. 在構造函數中綁定tick函數

class Clock extends React.Component{
 constructor(props){
   super(props);
   this.state={date: new Date()}
   this.tick=this.tick.bind(this)
 }
  1. 在setInterval方法中綁定tick函數
 componentDidMount() {
    this.timerID = setInterval(this.tick.bind(this),
      1000
    );
  }

從技術上講,如果this.tick()返回一個函數,您應該能夠使用第二個代碼片段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM