[英]Axios AJAX call in React returning only initial state
我正在尝试使用 React 中的 Axios 进行简单的 AJAX 调用,但我不知道我哪里出错了。
这是我到目前为止所拥有的(在我的组件中):
ComponentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/users')
.then( res => {
const users = res
this.setState({ users });
});
}
render() {
console.log(this.state.users) // returns the **initialised EMPTY array**
return (
<div>
{this.state.users.map( user => <p>{user.name}</p>)} // returns nothing
</div>
)
}
我正在.get()
方法中给定的 URL 上访问一个简单的数组.get()
如有必要,请查看它的结构)。 然后我链接.then()
承诺并在箭头函数中传递res
参数。
然后我将users
变量分配给结果,并尝试将状态设置为这样。 所以此时我希望 this.state.users 等于结果数组。
然而...
A) 当我尝试 console.log(this.state.users) 时,它返回初始化的空数组
B) 当我尝试渲染数组的映射时,再次遍历每个对象的name
属性,什么也没有。
我哪里错了?
错别字的一部分(如 Phi Nguyen 指出的),还有一些其他需要解决的问题:
1) Axios 使用响应对象解析 promise。 所以要得到你需要做的结果:
axios.get('https://jsonplaceholder.typicode.com/users')
.then( res => {
const users = res.data; // Assuming the response body contains the array
this.setState({ users });
});
在此处查看有关响应对象的文档: https : //github.com/mzabriskie/axios#response-schema
2)如果出现异常(您的请求失败),您可能想要处理它而不是吞下它。 所以:
axios.get('https://jsonplaceholder.typicode.com/users')
.then( res => {
const users = res.data; // Assuming the response body contains the array
this.setState({ users });
})
.catch(err => {
// Handle the error here. E.g. use this.setState() to display an error msg.
})
错字。 它应该是componentDidMount
而不是ComponentDidMount
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.