2016-10-21 162 views
1

因此,我有一個組件顯示一些從外部API獲取並保存到localStorage的數據。我已經放了一個執行這個工作的fetchData()函數,並且我從componentWillMount()中調用了這個函數。它看起來像這樣:ReactJS:如何在獲取數據後重新渲染組件

componentWillMount() { 
    this.fetchData(); 
    } 

    ... 

    fetchData() { 
    if(localStorage.myData === undefined) { 
     fetch(apiUrl,{ 
     method: 'GET', 
     headers: ... 
     }) 
     .then(function(data) { 
     localStorage.setItem('myData', data); 
     }).catch(function(error) { 
     // error handling 
     }) 
    } else { return true; } 
    } 

的這裏的想法是檢查數據是否在localStorage的設置每一個渲染,否則取水的時候,保存數據,然後重新呈現。但是,在將數據存儲在localStorage中後,我無法讓它重新渲染。我嘗試使用this.setState({data: data})代替fetchData函數,但未定義this

我在這裏做錯了什麼?提前致謝。

+2

您的類中的this'與'then()'函數內的'this'有不同的上下文。您需要適當地綁定您在當時使用的函數 –

+2

或使用箭頭函數 –

+0

http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html – m1r1k

回答

3

this在你的班上有一個不同的上下文比你那麼()函數內的this。爲了您的具體情況,你可以做以下

fetch(apiUrl,{ 
    method: 'GET', 
    headers: ... 
    }) 
    .then(function(data) { 
    // This now refers to your component 
    this.setState({data: data}); 
    }.bind(this)) 
    .catch(function(error) { 
    // error handling 
    }) 

或者作爲Utro建議,您可以使用arrow functions不會因此建立自己的背景讓您恰當地使用this

fetch(apiUrl,{ 
    method: 'GET', 
    headers: ... 
    }) 
    .then(data => { 
    // This now refers to your component 
    this.setState({data: data}); 
    }).catch(function(error) { 
    // error handling 
    }) 
+0

非常感謝您的解釋!我認爲箭頭函數與非箭頭函數完全相同,只是在語義上有所不同。這解釋了很多.. :) – Majoren

1

此對象在.then中將引用Promise對象而不是Component的對象。

vat that = this; 

宣佈的這個局部變量到,然後你可以使用

that.setState({})