【问题标题】:React Native this2.state errorReact Native this2.state 错误
【发布时间】:2017-04-18 23:09:19
【问题描述】:

我正在尝试从 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 的解决方案是什么?

【问题讨论】:

    标签: reactjs react-native setstate


    【解决方案1】:

    无论您在何处使用此 fetch,都可以绑定该函数或更改为箭头函数。 this 未绑定到组件,因此 this.setState 抛出错误。显示未处理的承诺拒绝错误,因为您没有设置 catch 语句来处理错误。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        可能的未处理承诺拒绝

        发生此错误是因为您没有按照您的承诺实现 catch

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-01-20
          • 2019-06-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-04
          • 2018-05-04
          • 1970-01-01
          相关资源
          最近更新 更多