React Native this2.state错误

时间:2017-04-18 23:09:19

标签: reactjs react-native setstate

我正在尝试从GET请求(这是一个对象数组)中获取响应,并将其状态设置为数组'模板',以便我以后可以访问它使用this.state.templates,如下:

  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行注释掉并且只是控制台记录响应时,我得到了正确的数组,所以我知道我的fetch是好的。但是,当我尝试运行setState行时,我收到此错误:

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

解决此错误并在渲染中使用this.state.templates会有什么解决方案?

3 个答案:

答案 0 :(得分:0)

  

可能未处理的承诺拒绝

发生此错误是因为您未在诺言上实施props.children

catch

答案 1 :(得分:0)

无论您何时使用此提取,请绑定该功能或更改为箭头功能。 this未绑定到组件,因此this.setState引发错误。未显示的promise promise rejection错误正在显示,因为您没有设置catch语句来处理错误。

答案 2 :(得分:0)

_this2.setState is not a function,通常,这不是你的参考组件,启动你的调试器并仔细检查this引用的是什么。我想您可以使用bindconst self = this来解决此问题。

看一下这篇文章可能会对您有帮助,https://www.sitepoint.com/bind-javascripts-this-keyword-react/