2017-10-12 29 views
0

我有以下工作代碼:ReactJS和「本」

fetchPost (id) { 
var mainObject = {}, 
    toReturn = [], 
    promises = []; 
var that = this; 

for(var i=id; i<10; i++) { 
    promises.push(axios.get(`api/posts/${i}`)); 
} 

axios.all(promises).then(function(results) { 
    results.forEach(function(response) { 
    toReturn.push(response.data); 
    console.log("toReturn: " + toReturn); 
    that.setState({ post: toReturn }); 
    }); 
}); 
} 

,但得到它的工作我不得不添加var that = this;使that.setState會工作。

使用this.setState會產生這個錯誤:

Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined

那麼,爲什麼我要使用這個技巧,我不明白得到這個示例代碼工作?這對我沒有任何意義。

+3

相信該變量在類/組件級別的作用域所以你必須在這一水平獲得任何東西。但是,如果您使用箭頭函數(結果)=> {... code},那麼您將獲得此類訪問權限。我相信承諾中的「這個」只會涉及承諾的範圍,並且能夠超出這個範圍。 –

+1

永遠在哪裏你正在調用fetchpost方法你只需要將「this」綁定到該方法,以便fetchpost方法知道你指的是哪個「this」對象,因爲你沒有在這裏綁定「this」,所以你指的是普通的「this」對象不是包含反應屬性和方法的對象 –

+0

這是正確的@dream_cap,因爲他使用了聲明函數而不是胖箭頭函數。一個胖箭頭函數可以從父類訪問它,而'this'的作用域只是fetchPost函數 – patrick

回答

1

我相信該變量的作用域是在類/組件級別,因此您可以訪問該級別的任何內容。但是,如果您使用箭頭函數(結果)=> {... code},那麼您將獲得此類訪問權限。我相信承諾中的「這個」只會涉及承諾的範圍,並且能夠超出這個範圍。

axios.all(promises).then((results) => { //changing to an arrow function where the arrow function does not bind it's own "this" scope 
    results.forEach((response) => { 
    toReturn.push(response.data); 
    console.log("toReturn: " + toReturn); 
    this.setState({ post: toReturn }); 
    }); 
}); 

下面是一些更information關於箭頭的功能和「本」:

No binding of this: Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.