因此,我有一個組件顯示一些從外部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
。
我在這裏做錯了什麼?提前致謝。
您的類中的this'與'then()'函數內的'this'有不同的上下文。您需要適當地綁定您在當時使用的函數 –
或使用箭頭函數 –
http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html – m1r1k