我有一個發送異步請求的按鈕,但我只想在變數為假時發送它。我試圖關注這個問題,但我不斷收到錯誤
這是原來的onClick
onClick={async () => {
const CompleteCA = async () => {
try {
// If status is draft, call sendTransaction
if (!statusFinal) {
await sendTransaction({
variables: {
input: {
CAId: CA.id,
},
},
});
}
await updateCA({
variables: {
id: CA,
},
});
history.push('/');
} catch (error) {
logError(error);
}
};
CompleteCA();
}}
添加條件后:
onClick={async () => {
testFlag ? alert("flag is true") :
const CompleteCA = async () => {
try {
...... rest of function
}
};
CompleteCA();
}}
由于無法在 onClick 中宣告 const,因此我將所有行都加了下劃線,但我不確定如何將其移至另一個函式并保持異步完整
uj5u.com熱心網友回復:
我建議單獨定義異步函式并將條件邏輯放在那里。然后從onClicklike中呼叫它<button onClick={async () => { await asyncFunc(); } }>Click</button>
這是一個簡單的 CodeSandbox 示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/421942.html
標籤:
上一篇:單擊觸發它創建的事件偵聽器
