【发布时间】: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。