[英]Handling form clear and submit message on successful submission - React
我正在嘗試在我的表單提交方法中添加幾行,以處理表單組件在提交時使用初始 state 值重新渲染。 我有它,以便我能夠正確發布,但是當它提交時,無法判斷它是否已正確提交並且表單中的數據保持不變。
有沒有比我在下面嘗試的方法更簡單的方法? 我只想在成功保存后重定向到新組件。
獲得成功消息是否包括以某種方式處理來自后端 API 的“res.send(200)”消息?
const DiveLogForm = (props) => {
....
// state for the current field value
const [dive, setDive] = useState({
diveTypeID: ``,
diveSchoolID: ``,
currentID: ``,
visibilityID: ``,
diveDate: ``,
diveMaxDepth: ``,
userID: props.user.userID,
diveVerifiedBySchool: false,
diveNotes: ``,
diveSpotID: ``,
redirectToForm: false,
error: '',
id: ''
});
.....
const jwt = auth.isAuthenticated()
...
function handleSubmitDive(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const formData = new FormData();
formData.append("diveTypeID", dive.diveTypeID);
formData.append("diveSchoolID", dive.diveSchoolID);
formData.append("currentID", dive.currentID);
formData.append("visibilityID", dive.visibilityID);
formData.append("diveDate", dive.diveDate);
formData.append("diveMaxDepth", dive.diveMaxDepth);
formData.append("userID", dive.userID);
formData.append("diveVerifiedBySchool", dive.diveVerifiedBySchool);
formData.append("diveNotes", dive.diveNotes);
formData.append("diveSpotID", dive.diveSpotID);
formData.append("photos", photos);
const config = {
headers: {
'content-type': 'multipart/form-data'
}
};
axios.post("http://localhost:5002/api/divelog/createdivelog", jwt.token, formData, config)
.then((data) => {
if (data && data.error) {
setDive({...dive, error: data.error})
} else {
setDive({...dive, 'redirectToForm': true})
}
})
}
// Make sure you declare this outside the component .
const initialValue = {
diveTypeID: ``,
diveSchoolID: ``,
currentID: ``,
visibilityID: ``,
diveDate: ``,
diveMaxDepth: ``,
userID: props.user.userID,
diveVerifiedBySchool: false,
diveNotes: ``,
diveSpotID: ``,
redirectToForm: false,
error: '',
id: ''
}
// Now in the state when initializing you can do this
const [ dive, setDive ] = useState(initialValue);
// In your handle submit when the request is successfull inside your then
setDive(initialValue);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.