我正在使用Axios
对后端进行API调用。问题是,我要拨打电话,然后将响应保存在一个挂钩中,而不是拨打另一个电话,然后将响应保存在相同的挂钩中。我必须在收到第一个调用的响应后再进行第二个调用,因为在我的后端,第二个调用监听EventEmmiter:
const [invoice,setInvoice] = useState({
loading: false,error: false,content: null,paid: false
});
function createInvoice() {
setInvoice({ ...invoice,loading: true });
api
.post("/lightning/createinvoice",{
amount: values.amount
})
.then(response => {
setInvoice({
loading: false,content: response.data,paid: false
});
return api.get("/lightning/invoicestatus",{
params: { id: response.data.id }
});
})
.then(response => {
if (response.data.status === "Confirmed")
setInvoice({ ...invoice,paid: true });
})
.catch(() => {
setInvoice({ loading: false,error: true,content: null });
});
}
此代码有效,但是我得到了invoices.content: null
。我怀疑setInvoice({ ...invoice,paid: true });
失败了,因为invoice
状态没有最新状态。
我应该如何解决?
预先感谢