可能的未处理的承诺拒绝(ID:0):undefined不是一个对象('prevComponentInstance._currentElement')

问题描述:

在反应原生我想使用axios.get(my_url_path)获取json数据,然后我更新我的状态与response.data为“urldatabase”键,如果我试图把这种状态键,从我得到的JSON读取的数据出现错误:可能的未处理的承诺拒绝(ID:0):undefined不是一个对象('prevComponentInstance._currentElement')

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} /> 
) 
} 
} 

任何人都可以请解释为什么我得到这个错误?我做错了,如果有的话?

+0

你可以尝试绑定组件在你的构造函数中挂载吗?也请添加适当缩进的整个文件。 this.state = {...}在构造函数中,加入: ''javascript this.componentWillMount = this.componentWillMount.bind(this); ''' –

考虑:在componentWillMount,如果axios承诺被拒绝会发生什么?对:没有处理。在那里你需要一个catch处理程序。承诺的基本原则:始终处理拒绝或将承诺退还给调用者。在这种情况下,如果您退回componentWillMount的承诺,那么React将不会执行任何操作,您需要处理componentWillMount内的错误。

重新编写这样的代码并检查它是否再次发生。

} 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] && this.state.urldatabase[num].book; // this code can avoid undefined error 
    return(
     <RiddleHeader headerText={book} />) } }