アキシャスでゲット応答の状態を設定するにはどうすればよいですか?反応のアキシャスからの応答の状態を設定する方法
axios.get(response){
this.setState({events: response.data})
}
アキシャスでゲット応答の状態を設定するにはどうすればよいですか?反応のアキシャスからの応答の状態を設定する方法
axios.get(response){
this.setState({events: response.data})
}
ここでは構文エラーがあります。代わりに
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 herethis
キーワードは、呼び出される場所によって異なる値を持ちます。 this
in this.setState
はコンストラクタオブジェクトを参照し、関数内でthis
を呼び出すと、window
オブジェクトを参照します。だから私はにthis
を割り当てました。あなたはmore about this hereProの先端を読むことができます:
あなたは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);
});
「これ」が腋窩の内部で異なるため、これは機能しません。 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 });
});
せずに同じ効果を取得する必要があります私が反応することを学んでいた過去のそれまで。私がしたことは、componentDidMount
メソッドにapiコールをかけて、状態を初期値に設定しました。私は、データがフェッチされている間にローダーを使用しました。
componentDidMount() {
const self = this;
axios.get(response){
self.setState({ events: response.data });
}
今のところ、私はcheckenrodeと同様のものを使用します。
このような何か:私もやってしまったものだ
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})
})
を。 – Ksenia
これは正解です。ありがとう@abdellah – Dipesh