2016-12-17 15 views

答えて

38

ここでは構文エラーがあります。代わりに

var self = this; 
axios.get('/url') 
.then(function (response) { 
    console.log(response); 
    self.setState({events: response.data}) 
}) 
.catch(function (error) { 
    console.log(error); 
}); 
//the rest of the code 
var a = 'i might be executed before the server responds' 

ここで注意すべきいくつかのことがあり、これを試してみてください:

  • axios.getは、ときのレスポンスコードの残りの部分は.ANDを実行されることを意味する非同期関数でありますサーバが到着すると、thenに渡された関数が実行されます。戻り値axios.get('url')は約束オブジェクトと呼ばれます。読むことができますmore about it here
  • thisキーワードは、呼び出される場所によって異なる値を持ちます。 this in this.setStateはコンストラクタオブジェクトを参照し、関数内でthisを呼び出すと、windowオブジェクトを参照します。だから私はにthisを割り当てました。あなたはmore about this here

Proの先端を読むことができます:

あなたはES6を使用する場合は、あなたが(this自分自身を持っていません)矢印の関数を使用して変数にthisを割り当てずthis.setStateを使用したいと思います。 more about it here

axios.get('/url') 
    .then((response) => { 
     console.log(response); 
     this.setState({events: response.data}) 
    }) 
    .catch((error)=>{ 
     console.log(error); 
    }); 
+1

を。 – Ksenia

+1

これは正解です。ありがとう@abdellah – Dipesh

14

「これ」が腋窩の内部で異なるため、これは機能しません。 axiosの中の "this"は、あなたの反応コンポーネントではなくaxiosオブジェクトを指します。 .bindでこれを解決できます

また、Axios is notが正しく使用されています。

それは私が同様の約束を扱っていますが、矢印関数の関数アウトサブES6を可能性が使用している場合は別の方法として

axios.get("/yourURL").then(function(response) { 
    this.setState({ events: response.data }); 
}.bind(this)); 

のようなものを見て、バインド

axios.get("/yourURL").then(response => { 
    this.setState({ events: response.data }); 
}); 
0

せずに同じ効果を取得する必要があります私が反応することを学んでいた過去のそれまで。私がしたことは、componentDidMountメソッドにapiコールをかけて、状態を初期値に設定しました。私は、データがフェッチされている間にローダーを使用しました。

componentDidMount() { 
const self = this; 
axios.get(response){ 
    self.setState({ events: response.data }); 
} 

今のところ、私はcheckenrodeと同様のものを使用します。

0

このような何か:私もやってしまったものだ

var self= this; // self will now be referred to your component 

    axios.get("http://localhost:3001/get_user?id=" + id) 
    .then(function (response) { 
    if(response.data.rows != null) 
    user_detail = response.data.rows; 
    console.log(response); 
    self.setState({email: user_detail.name, name: user_detail.name}) 
    }) 
関連する問題