2017-10-19 16 views
-2

ネイティブに反応して、axson.get(my_url_path)を使用してjsonデータを取得しようとしています。未解決のプロミス拒否(id:0):未定義はオブジェクトではありません( '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} /> 
) 
} 
} 

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

私のコードは次の通りである:私は、この状態のキーを呼び出し、私が得たJSONからデータを読み取ろうと場合にresponse.dataでキー「urldatabase」、私はエラーを取得します

誰でもこのエラーが発生する理由を説明していただけますか?もし私が何か間違っていたら?

+0

コンポーネントをコンストラクタにバインドできませんでしたか?適切なインデントを付けてファイル全体を追加してください。 コンストラクタのthis.state = {...}の後に、これを追加します。 '' 'javascript this.componentWillMount = this.componentWillMount.bind(this); '' ' –

答えて

1

考えてみましょう:componentWillMountでは、Axiosの約束が拒否されたらどうなりますか?右:それは未処理です。そこにはcatchハンドラが必要です。約束の基本的なルール:常に拒否を処理するか、約束を呼び出し元に返します。この場合、ReactはcomponentWillMountの約束を返せば何もしませんので、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} />) } } 
関連する問題