【问题标题】:Why does my axios call return undefined even after then is resolved?为什么我的 axios 调用即使在解决之后仍返回 undefined?
【发布时间】:2021-02-16 12:42:03
【问题描述】:

我目前正在使用函数来预定义我所有的 axios 调用,例如:

export const getClients = () => {
    axios.get("/client/")
        .then(response=>{
            return response;
        })
        .catch(error=>{
            return error;
        });
    };

现在,我想在 componentDidMount 中的基于类的组件中调用它,如下所示:

  componentDidMount(){
        this.setState({
            clients: getClients()
        });
  }

我似乎无法弄清楚为什么当我在componentDidMount 末尾尝试console.log(this.state.clients) 时出现未定义的错误。我是 React 的新手,据我了解,axios 调用函数中的 then 应该解决承诺并从 API 调用返回实际响应,所以当我调用 getClients() 时,clients 状态应该成为回应。

我做错了什么?

【问题讨论】:

  • getClients()这是一个承诺,你需要await加上retun里面getClients
  • 感谢您的回复。那么,应该是export const getClients = async ()....还是别的什么?
  • 在你调用它的地方使用 await。

标签: reactjs axios


【解决方案1】:
 componentDidMount(){
       fetchClients();    
  }

  const fetchClients = () => {
    getClients().then( (response)=> {
      // handle success
             this.setState({clients:response});

    });
  };

【讨论】:

    【解决方案2】:

    好的,这里有一些东西需要清除:-

    1. 您需要像这样更改getClients:-
    export const getClients = () => {
        return axios.get("/client/")
            .then(response=>{
                return response;
            })
            .catch(error=>{
                return error;
            });
        };
    

    为什么? 因为您从 then 的回调中返回的值隐式包装在 Promise 中,并且必须像在 function sum(a,b) {return a+b} 之类的函数中一样返回以供使用

    1. componentDidMount 会变成这样:-
    componentDidMount(){
           const fetchClients = async () => {
                const clients = await getClients();
                 this.setState({clients});
             }
           fetchClients();    
      }
    

    为什么? 如果您想以声明方式使用getClients 而不是.then().then() 承诺链,您将首先将其包装在async 函数中,然后在getClients() 上调用await(请记住此函数返回Promise ) 然后在该异步函数中设置状态。

    1. 即使您在componentDidMountfetchClients() 之后console.log 处于clients 状态,您也可能看不到设置的值,因为setState 是异步工作的。所以千万不要在设置之后就依赖你所在州的console.log

    【讨论】:

    • 谢谢,但我现在收到Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined
    • 将 fetchClients 从常规函数更新为箭头函数。现在试试。
    • 现在可以了。还有一个问题,为什么它现在可以使用箭头功能而不是常规功能,因为它们都是异步的?另外,await getClients() 可以更改为 .then(..) 吗?
    • 箭头函数从它们的词法外部作用域获取“this”值,而在外部作用域中,“this”的值是类组件实例本身。常规功能不能那样工作。我会鼓励你阅读更多关于它们的信息。很多事情发生在幕后。是的,await getClients() 可以更改为 getClients().then(res=>setState.....)。在这种情况下,您不需要该包装器异步函数。
    猜你喜欢
    • 1970-01-01
    • 2019-03-29
    • 2021-07-12
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多