我从react函数返回数组的错误在哪里?



所以我有一个react函数,这是一个api调用,并获得一些数据,我想只是返回的状态,回到父组件。

我的代码

父组件函数

//this is called via a button with a state passed down to the function
async function scheduleParent(){
const returned = await ScheduleChild(data)
console.log(returned)
}

子函数

export default async function ScheduleChild(data){
await axios({
method: "POST",
url: //myapi,
data: {data}
}).then(res => {
console.log(res)
return(res)
}).catch(err => {
console.log(err)
return(err)
});  

当console.log(返回)被调用时,我得到未定义。

您从回调函数返回,而不是从SchedulePayment返回。您应该在api调用之前添加return以便工作。或者用一种更好的方式

export default async function SchedulePayment(data){
try {
const res = axios.post(<api-url>, data)
return res
} catch (err) {
console.log(err)
return(err)
}
}

相关内容

最新更新