[英]How to set state of response from axios in react
如何在 axios 中設置 get 響應的狀態?
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
是一個異步函數,這意味着其余的代碼將被執行。當服務器的響應到達時,傳遞給then
的函數將被執行。 axios.get('url')
的返回值稱為promise 對象。 你可以在這里閱讀更多關於它的信息this
關鍵字具有不同的值,具體取決於它被調用的位置。 this
在this.setState
應該指的是構造函數對象,當你調用this
函數內部,它指的是window
對象。 這就是我將this
分配給變量self
。 您可以在此處閱讀有關此內容的更多信息專家提示:
如果您使用 ES6,您會想要使用箭頭函數(它們沒有自己的this
)並使用this.setState
而不將this
分配給變量。 更多關於它在這里
axios.get('/url')
.then((response) => {
console.log(response);
this.setState({events: response.data})
})
.catch((error)=>{
console.log(error);
});
這是一個完整的示例https://codesandbox.io/s/rm4pyq9m0o,其中包含通常用於獲取數據的最佳實踐,包括錯誤處理、重試和加載。 這提供了更好的用戶體驗。 我們鼓勵您修改代碼並嘗試獲得更多有關它的見解。
這不起作用,因為“this”在 axios 內部是不同的。 axios 中的“this”指的是 axios 對象,而不是您的 react 組件。 您可以使用 .bind 解決此問題
axios 也沒有被正確使用。
它應該看起來像
axios.get("/yourURL").then(function(response) {
this.setState({ events: response.data });
}.bind(this));
或者,如果使用 es6,您可以將函數分出箭頭函數並在不綁定的情況下獲得相同的效果
axios.get("/yourURL").then(response => {
this.setState({ events: response.data });
});
簡單試試這個節點js
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
如果您使用的是react js那么您首先在組件中導入而不是使用 axios
像這樣:
import React from 'react';
import axios from 'axios';
export default class PersonList extends React.Component {
state = {
persons: []
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}
render() {
return (
<ul>
{ this.state.persons.map(person => <li>{person.name}</li>)}
</ul>
)
}
}
我在學習 React 時處理過類似於過去的 promise。 我所做的是將 api 調用放在componentDidMount
方法上,並將狀態設置為初始值。 我在獲取數據時使用了加載程序。
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})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.