【问题标题】:Axios AJAX call in React returning only initial stateReact 中的 Axios AJAX 调用仅返回初始状态
【发布时间】:2017-02-17 09:34:30
【问题描述】:

我正在尝试在 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() 承诺并在箭头函数中传递res 参数。

然后我将users 变量分配给结果,并尝试将状态设置为this。 所以此时我希望 this.state.users 等于结果数组。

不过……

A) 当我尝试 console.log(this.state.users) 时,它返回初始化的空数组

B) 当我尝试渲染数组的映射时,再次遍历每个对象的 name 属性,什么也没有。

我哪里出错了?

【问题讨论】:

    标签: javascript arrays ajax reactjs axios


    【解决方案1】:

    错字的一部分(正如 Phi Nguyen 指出的那样),还有一些需要修复的地方:

    1) Axios 使用响应对象解析承诺。所以要得到你需要做的结果:

       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.
       })
    

    【讨论】:

    • 那行得通 - 谢谢。不过我有点困惑 - 当我 console.log 结果时,返回两个值:[],以及来自 API 的预期数组。这大概可以通过在初始化时返回一次状态值来解释,然后再次使用 componentDidMount。但是,当我尝试访问数组中的单个对象时,例如this.state.users[0],它会尝试访问空数组。我只能通过数组映射来获得它。有没有办法每次都针对更新的this.state.users 值,避免拉入初始状态值?
    • 每次调用this.setState,都会再次调用render方法来反映组件的新状态。在此处查看此图表:imgh.us/react-lifecycle.svg 因此,您有一个初始渲染(当用户未初始化时),然后在 componentDidMount 之后有第二个渲染,在调用 setState 之后有第三个渲染(此时您有用户列表)。您可以在组件构造函数中初始化列表。通常在渲染方法中你可以检查this.state.users是否为空并显示一个加载器或其他东西。
    【解决方案2】:

    错字。应该是componentDidMount 而不是ComponentDidMount

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      相关资源
      最近更新 更多