希望你們都好。
我遇到了一個問題,我找不到簡明的答案,所以我要在這里尋求幫助。
我有一個試圖在我的 React 組件中呼叫的函式:
// Open up calendar day if today is equal to day in API.
const [openCalendarBox, setOpenCalendarBox] = useState('');
// Call on post method via axios
const openCalendarChocolateBox = async (event) => {
event.preventDefault();
if (date) {
// Url where to post
await axios.post(`http://localhost:5001/open/chocolate`, {
day: date,
});
alert('New day is available to eat!');
}
setOpenCalendarBox('');
};
openCalendarChocolateBox();
但是當我呼叫該函式時,它并沒有像預期的那樣作業,而是在控制臺中收到此錯誤:
Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'event.preventDefault')
我該如何解決這個問題?我嘗試在我的引數中洗掉事件引數,但我仍然希望在呼叫我的函式時防止頁面重新加載多次或根本不重新加載。
提前感謝您的任何幫助,請保重。
uj5u.com熱心網友回復:
如果要在組件加載時加載它,則不需要事件偵聽器。只需將代碼移動到一個useEffect()帶有空依賴陣列的鉤子(只會在組件加載時運行)。
useEffect(() => {
if (date) {
// Url where to post
await axios.post(`http://localhost:5001/open/chocolate`, {
day: date,
});
alert('New day is available to eat!');
}
setOpenCalendarBox('');
}, [])
新的問題,從哪里來date?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/393491.html
標籤:javascript 反应
上一篇:使用物件鍵作為另一個物件的鍵
下一篇:如何根據按鈕點擊更新文本?
