我试图在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 (
{this.state.users.map( user =>
{user.name}
)} // returns nothing)
}
我正在访问.get()方法中给出的URL处的一个简单数组(如果需要,请查看它的结构)。然后我链接.then()承诺并在箭头函数中传递res参数。
然后我将users变量分配给结果,并尝试将状态设置为此。 所以在这一点上,我希望this.state.users等于生成的数组。
然而......
A)当我尝试console.log(this.state.users)时,它返回初始化的空数组
B)当我尝试渲染数组的映射时,再次遍历每个对象的name属性。
我哪里错了?