2017-04-18 114 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); 
});