[英]React - Unhandled Rejection (TypeError): e.preventDefault is not a function
當我嘗試使用react-hook-form
實現 Axios 帖子時,出現以下錯誤:
Unhandled Rejection (TypeError): e.preventDefault is not a function
當我將onSubmit={handleSubmit(handleSubmitAxios)}
添加到我的<form>
時,問題開始出現。 基本上,我希望我的表單由react-hook-form
控制,使用與我的后端通信的自定義handleSubmitAxios
后調用。
這是我的登錄組件,目前只是測試 react-hook-form 的功能,但是e.preventDefault
消息讓我感到困惑。
export default function SignIn()
{
const { register, control, errors: fieldsErrors, handleSubmit } = useForm()
const history = useHistory();
const initialFormData = Object.freeze({
email: '',
password: '',
});
const [formData, updateFormData] = useState(initialFormData);
const handleChange = (e) => {
updateFormData({
...formData,
});
};
const dispatch = useDispatch();
const handleSubmitAxios = (e) => {
e.preventDefault();
console.log(formData);
axiosInstance
.post(`auth/token/`, {
grant_type: 'password',
username: formData.email,
password: formData.password,
})
.then((res) => {
console.log(res);
localStorage.setItem('access_token', res.data.access_token);
localStorage.setItem('refresh_token', res.data.refresh_token);
history.push('/');
window.location.reload();
dispatch(login({
name: formData.email,
password: formData.password,
loggedIn: true,
}))
})
};
const classes = useStyles();
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form} noValidate onSubmit={handleSubmit(handleSubmitAxios)}>
<FormControl fullWidth variant="outlined">
<Controller
name="email"
as={
<TextField
variant="outlined"
margin="normal"
inputRef={register}
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
onChange={handleChange}
helperText={fieldsErrors.email ? fieldsErrors.email.message : null}
error={fieldsErrors.email}
/>
}
control={control}
defaultValue=""
rules={{
required: 'Required',
pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
message: 'invalid email address'
}
}}
/>
</FormControl>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={handleSubmit}
>
Sign In
</Button>
</form>
</div>
</Container>
);
}
感謝您就如何解決原始錯誤提供任何幫助或指導!
根據文檔,第一個參數是data or errors
object,第二個參數是form event
。
((數據:Object,e?:事件)=> 無效,(錯誤:Object,e?:事件)=> 無效)=> Z86408593C34AF77FDD1Z0DF932F8B526
在您的情況下, e
是數據,這就是您收到e.preventDefault
is not a function 錯誤的原因。
像這樣試試
const handleSubmitAxios = (data, e) => {
e.preventDefault(); // Actually, you don’t need to call this, Because it’s already called inside react hook form.
console.log(data)
.....
但是, react-hook-form
已經阻止了默認的表單事件,不知道你為什么要再次這樣做。 檢查此屏幕截圖一次並進行演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.