2017-04-18 109 views
0

我試圖從一個GET請求(這是一個對象數組)中獲取響應,並將其狀態設置爲一個數組「模板」,以便以後可以使用它進行訪問。 state.templates,像這樣:React Native this2.state錯誤

fetch('https://tiy-warmup.herokuapp.com/api/templates?token=' + 
    token) 
    .then(response => response.json()) 
    .then(response => this.setState({templates: response})) 
    // .then(response => console.log(response)) 

當我擁有的setState行註釋掉,只是控制檯日誌的反應,我得到正確的陣列回來了,所以我知道我取好。然而,當我嘗試運行的setState線,我得到這個錯誤:

Possible Unhandled Promise Rejection (id: 0): 
_this2.setState is not a function 

什麼將避過這一錯誤,並能夠在渲染使用this.state.templates的解決方案?

回答

0

無論你正在使用這個取,要麼綁定功能或者改變箭頭的功能。 this未綁定到組件,因此this.setState正在引發錯誤。未處理的承諾拒絕錯誤正在顯示,因爲您沒有設置用於處理錯誤的catch語句。

+0

謝謝!箭頭功能工作。 –

0

Possible Unhandled Promise Rejection

這個錯誤是因爲你沒有在你的承諾落實catch

.catch(error => { 
    console.log('There has been a problem with your fetch operation: '+ error.message); 
});