2017-08-16 118 views
1

我不明白在一個React應用程序中的香草JavaScript和ES6之間的語法差異。 我不工作的第一代碼是setState函數在使用ES6語法的React中未定義?

class App extends Component{ 
constructor(props){ 
super(props); 

this.state = {videos:[]}; 

YTSearch({key: API_KEY,term :'surfboards'},function(videos){ 
    this.setState({videos : videos}); 
}); 
} 

這給在控制檯

錯誤「未定義的‘一’不能讀取屬性」的setState但改變語法

YTSearch({key: API_KEY,term :'surfboards'},(videos)=>{ 
    this.setState({videos : videos}); 
}); 

解決了這個問題。是不是都一樣的東西(我可能是錯的)。採用

function(videos){} 

(videos) => {} 

我不舒服的javascript,所以任何幫助表示讚賞。

+3

的可能的複製[Arrow功能VS函數聲明/表情:他們當量/更換?](https://開頭計算器。 com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch) – 4castle

回答

4

這是由於this被綁定。

當使用箭頭功能this仍然綁定到您的App類。

但是,當您使用function關鍵字this綁定到該函數。

按MDN

直到箭頭的功能,每一個新的功能定義自己的這個值。

使用function關鍵字可以採取兩種方法。

首先,

YTSearch({key: API_KEY,term :'surfboards'}, function(videos){ 
    this.setState({ 
     videos : videos 
    }); 
}.bind(this)); 

,否則你可以這樣做:

//assign this to new variable that to use when setting state 
let that = this; 

YTSearch({key: API_KEY,term :'surfboards'}, function(videos){ 
    that.setState({ 
     videos : videos 
    }); 
}); 
+0

如果你不介意你能否展示我將如何使用函數關鍵字編寫上述代碼。 – Buttersnips

+0

@Buttersnips看到更新的答案,這是你想要的嗎? –

+0

是的。幫助我。 – Buttersnips

2

指的是工作。 我建議使用ES6箭頭功能:

class App extends Component{ 
    constructor(props){ 
    super(props); 

    this.state = {videos:[]}; 

    YTSearch({key: API_KEY,term :'surfboards'}, (videos) => { 
     this.setState({videos : videos}); 
    }); 
    } 
} 

這是因爲箭頭功能不會創建自己的,在封閉執行上下文的這個值被使用。 您還可以存儲在變量(或綁定功能)參考這個

class App extends Component{ 
    constructor(props){ 
    super(props); 

    var _this = this; 

    this.state = {videos:[]}; 

    YTSearch({key: API_KEY,term :'surfboards'}, function(videos){ 
     _this.setState({videos : videos}); 
    }); 
    } 
} 
相關問題