2016-04-18 5 views
8

fetch関数を使用して受け取ったpromiseから状態を更新しようとしています。プロミスのthen関数からsetStateを設定できませんでした

componentDidMount(){ 

fetch(url).then((responseText) => { 

    var response = responseText.json(); 

    response.then(function(response){ 
     this.setState(response); 
    }); 

    }); 
} 

IはsetState関数そして

ないというエラーを取得し、私は以下のようthis値を渡すbind(this)しようとしました。

componentDidMount(){ 

fetch(url).then((responseText) => { 

    var response = responseText.json(); 

    response.then(function(response){ 
     this.setState(response); 
    }); 

    }).bind(this); 
} 

現在は動作していません。もう一度同じエラーが発生します。

答えて

4

申し訳ありません、ただ今、this変数を正しくバインドしていないことがわかりました。

今、修正されています。

componentDidMount(){ 

fetch(url).then((responseText) => { 

    var response = responseText.json(); 

    response.then(function(response){ 
     this.setState(response); 
    }); 

    }.bind(this)); 
} 
+0

私は皮肉なことに、このメソッドを読むことができます。 – ApertureSecurity

0

あなたの2番目の約束は、現在のコンテキストがthisではありません。矢印関数もここで使用できます。

componentDidMount(){ 
    fetch(url).then((responseText) => { 
    return responseText.json(); 
    }) 
    .then((response) => { 
    this.setState(response); 
    }); 
} 

また、連鎖する代わりに、あなたの約束を入れ子にすることは読みやすさを支援し、あなたがcallback hellを避けるために役立つかもしれません。

14

これはthisの有効範囲があるためです。Function.prototype.bindを使用しようとしているときに何かをしています。あなたの間違いは、最後の無名関数に至るまで縛らないことです。あなたはおそらく、やりたいことは、このように、すべての方法を使用する矢印の機能である:

componentDidMount(){ 
    fetch(url) 
     .then((responseText) => responseText.json()) 
     .then((response) => this.setState(response)); 
} 

アロー関数は常にthisのコンテキストを維持します。