javascript - React 中的 Axios AJAX 调用仅返回初始状态

标签 javascript arrays ajax reactjs axios

我正在尝试在 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 中的一个简单数组(如有必要,请查看它的结构)。然后我链接 .then() promise 并在箭头函数中传递 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.
   })

关于javascript - React 中的 Axios AJAX 调用仅返回初始状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39933267/

相关文章:

javascript 正则表达式模式验证

javascript - Async.map - 让它忽略错误,并处理整个列表

javascript - Rails 模态表单 - 在表单提交失败后使用 html.erb 文件中的内容更新弹出窗口

javascript - jquery 接收文本区域中输入的文本并将其传递给后端处理程序(perl、php 等)

javascript - ExtJS 等待多个商店加载

c - 初始化指针时,字符串文字与 char 数组

php - 通过 AJAX 从 PHP 发回多个结果

ajax - knockout SPA Ajax 加载模板

javascript - 如何使用 CsQuery 删除 html 内容中的所有脚本标签

c++ - std::sort() C++ 不工作但它很简单,为什么 :( 一维数组