[英]Submit button in a form works after the second click. ReactJS
我正在 React 電子商務項目中處理一個表單。
以下是它的工作方式:當用戶填寫表單並單擊提交按鈕時,我想將表單數據發布到服務器並將用戶重定向到確認/感謝頁面。
不幸的是,當我填寫表單並單擊提交按鈕時,以下代碼以特定方式工作:
第一次點擊 - 它發送數據但“setSubmitted(true)”不起作用所以我沒有被重定向
第二次點擊 - 再次發送數據,setSubmitted 工作,我被重定向
你能告訴我如何修復代碼嗎?
let history = useHistory();
const [submitted, setSubmitted] = useState(false);
const handleSubmit = (e) => {
e.preventDefault();
fetch('http://localhost:8000/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ cart: 1 }), //dummy data
})
.then((response) => {
setSubmitted(true);
return response.json();
})
.then(() => {
if (submitted) {
return history.push('/thank-you-page');
}
});
};
return (
<form onSubmit={handleSubmit}> ... </form>
);
您需要從第二個 then(...) 中刪除if statement
,因為狀態更新異步運行,並且在第一次單擊時為false
。 當您再次單擊表單提交然后提交時,這次從您的上次操作和您重定向是正確的。
還有一個,如果您使用從第一個then(...)
塊返回的 using 數據,您也可以將它們重定向代碼並刪除第二個。
const handleSubmit = (e) => {
e.preventDefault();
fetch('http://localhost:8000/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ cart: 1 }), //dummy data
})
.then((response) => {
setSubmitted(true);
return history.push('/thank-you-page');
});
};
希望這能解決您的問題。
setState
是一個異步操作,會導致重新渲染。 因此,您的組件在第一次單擊時執行的步驟是設置狀態並返回 json,這意味着在執行第二個.then()
(在第一次渲染時)提交的仍然是 false,通過第二次單擊時的第二次渲染將提交從上一次單擊設置為 true,然后它會進行歷史推送。
由於您僅使用此狀態來檢查是否推送到下一頁,因此您可以將其替換為 useRef,但我個人傾向於像這樣重新編寫它以避免任何混淆:
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch('http://localhost:8000/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ cart: 1 }), //dummy data
});
// setSubmitted(true); // set this still if you need it elsewhere
history.push('/thank-you-page');
// return response.json(); // only return this if you need it to be used somewhere
} catch(error) {
// handleTheErrorSomehow(error)
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.