我使用一个表单来捕获用户的输入。但一旦用户单击submit按钮,页面就会重新加载。我不想让它重新加载。这就是我决定使用preventDefault()方法的原因。
我怎样才能让它工作?
const handleHeaderValueUpdate = async ( headerId, e) =>{
e.preventDefault()
console.log(headerId)
setUpdating(true)
const updatedHeaderValue = {
username: user.username,
websiteName,
sitesubName,
};
if(file){ //logic behind uploading image and the image name
const data = new FormData();
const filename = Date.now() + file.name;
data.append("name", filename);
data.append("file", file);
updatedHeaderValue.headerImg = filename;
try{
await axios.post("/upload", data)//handles the uploading of the image
//setUpdated(true)
}catch(err){
dispatch({type: "UPDATE_FAILURE"})
}
}
try{
await axios.put("/headervalue/" + headerId, updatedHeaderValue)
setUpdating(false);
setTextUpdate(true)
//setUpdated(true)
}catch(err){
console.log(err)
}
}
<form onSubmit={()=>handleHeaderValueUpdate(headerId)} className="dashboard-form">
<div className='dasboard-input-div'>
<p className="dashboard-label">Website Name</p>
{dashboardEditMode ? <input className="dashboard-input" type="text" placeholder={singleValues.websiteName} autoFocus
onChange={(e) => setWebsiteName(e.target.value)}
required
/> :
<input className="dashboard-input" type="text" placeholder= {singleValues.websiteName} readOnly/>
}
</form>
这是提交按钮
{dashboardEditMode && <button className={updating ? "updateModeBTN-unclick updateModeBTN" : "updateModeBTN"} type="submit">Update</button>}