2017-10-19 66 views
-2

在反應原生我想使用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); ''' –

回答

1

考慮:在componentWillMount,如果axios承諾被拒絕會發生什麼?對:沒有處理。在那裏你需要一個catch處理程序。承諾的基本原則:始終處理拒絕或將承諾退還給調用者。在這種情況下,如果您退回componentWillMount的承諾,那麼React將不會執行任何操作,您需要處理componentWillMount內的錯誤。

0

重新編寫這樣的代碼並檢查它是否再次發生。

} 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} />) } } 
相關問題