【发布时间】:2021-07-22 17:14:15
【问题描述】:
这是一个发出 Axios.get() 请求的函数:
const mentorName = (value) => {
try {
const res = Axios.get(
`${BASE_URL}/api/v1/consultations/${value}`
)
if (res.status !== 200 || res.data.status !== "success") {
console.log(res)
return
}
} catch (error) {
console.log(error)
}
}
以下是控制台的输出:
Please Click here to see console output
现在,我想访问 res.data.data.consultant 但是当我尝试这样做时。它说 res.data 无效。这可能是因为它包含在一个承诺中。请帮我告诉如何访问它???
编辑:
按照建议使用 async/await:
const mentorName = async (value) => {
try {
const res = await Axios.get(
`${BASE_URL}/api/v1/consultations/${value}`
)
if (res.status !== 200 || res.data.status !== "success") {
console.log(res)
return
}
} catch (error) {
console.log(error)
}
}
Async/await 给出以下错误: 对象作为 React 子级无效(找到:[object Promise])。
编辑 2:
mentorName 在 array.map((row, index)) 中使用。我很确定调用该函数没有任何问题。
<TableCell align="left">
{mentorName(row.consultantID)}
</TableCell>
【问题讨论】:
-
要使用 axios,你需要使用 aysnc/await。尝试将
mentorName转换为异步函数,然后等待Axios.get? -
不!编写 async 和 await 后,程序给出错误“对象作为 React 子项无效(找到:[object Promise])”
-
@ParasBansal 我的建议不是答案。请编辑问题以显示您尝试过的内容。
-
我编辑了这个问题。请再次查看。
-
给出的错误与示例中的代码无关。您可能会将对象直接转储到反应组件中。
标签: javascript reactjs promise axios