可能未处理的承诺拒绝 (id: 0): undefined 不是一个对象 ('prevComponentInstance._currentElement') [英] Possible Unhandled Promise Rejection (id: 0): undefined is not an object ('prevComponentInstance._currentElement')

查看:91
本文介绍了可能未处理的承诺拒绝 (id: 0): undefined 不是一个对象 ('prevComponentInstance._currentElement')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在本机反应中,我尝试使用 axios.get(my_url_path) 获取 json 数据,然后我将使用 response.data 更新我的状态到 'urldatabase' 键,如果我尝试调用此状态键并读取数据从我得到的 json 中我得到错误:

In react native I am trying to get json data using axios.get(my_url_path), then I'm update my state with response.data to 'urldatabase' key ,if I trying to call this state key and read the data from the json that I got I get the error:

Possible Unhandled Promise Rejection (id: 0): undefined is not an object ('prevComponentInstance._currentElement').... 

我的代码如下:

  }
  constructor(props) {
    super(props);
    this.state = { userAnswer: '', count: 0, urldatabase: {} };
  }



  componentWillMount(){
    axios.get('my_url_path')
      .then(response => this.setState({urldatabase: response.data}));
  }
  render() {
    let num = this.state.count;
    console.log(this.state.urldatabase[num].book)
    const book = this.state.urldatabase[num].book
     return(
        <RiddleHeader headerText={book} />
)
}
}

谁能解释一下为什么我会收到这个错误?如果有的话,我做错了什么?

Can anyone please explain why am I getting this error? what I done wrong if any?

推荐答案

考虑:在 componentWillMount 中,如果 axios 承诺被拒绝会发生什么?正确:未处理.你需要一个 catch 处理程序.Promise 的基本规则:始终处理拒绝或将 Promise 返回给调用者.在这种情况下,由于如果您从 componentWillMount 中返回 promise,React 不会对它做任何事情,因此您需要在 componentWillMount 中处理错误.

Consider: In componentWillMount, what happens if the axios promise is rejected? Right: It's unhandled. You need a catch handler in there. The basic rule of promises: Always handle rejection or return the promise to the caller. In this case, since React won't do anything with it if you return the promise out of componentWillMount, you need to handle the error within componentWillMount.

这篇关于可能未处理的承诺拒绝 (id: 0): undefined 不是一个对象 ('prevComponentInstance._currentElement')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆