【发布时间】:2017-05-02 20:50:24
【问题描述】:
如何在 axios 中设置 get 响应的状态?
axios.get(response){
this.setState({events: response.data})
}
【问题讨论】:
标签: javascript reactjs axios
如何在 axios 中设置 get 响应的状态?
axios.get(response){
this.setState({events: response.data})
}
【问题讨论】:
标签: javascript reactjs axios
这里有语法错误。你应该试试这个
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 对象。你可以阅读more about it here
this 关键字具有不同的值,具体取决于调用它的位置。 this.setState中的this应该指的是构造函数对象,而当你在函数内部调用this时,它指的是window对象。这就是我将this 分配给变量self 的原因。你可以阅读more about this here
专业提示:
如果你使用 ES6,你会想要使用箭头函数(它们没有自己的 this)并使用 this.setState 而不将 this 分配给变量。 more about it here
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 时,我处理过类似于过去的承诺。我所做的是将 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})
})
【讨论】: