React - 未处理的拒绝(TypeError):e.preventDefault 不是函数

React - Unhandled Rejection (TypeError): e.preventDefault is not a function

当我尝试使用 react-hook-form 实现 Axios post 时出现以下错误:

Unhandled Rejection (TypeError): e.preventDefault is not a function

当我将 onSubmit={handleSubmit(handleSubmitAxios)} 添加到我的 <form> 时,问题开始出现。基本上,我希望我的表单由 react-hook-form 控制,使用与我的后端通信的自定义 handleSubmitAxios post 调用。

这是我的登录组件,目前只是测试 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>
    );
}

感谢您对我如何解决原始错误的任何帮助或指导!

根据 docs,第一个参数是 data or errors 对象,第二个参数是 form event

((data: Object, e?: Event) => void, (errors: Object, e?: Event) => void) => Function

在你的情况下 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 已经阻止了默认表单事件,不确定您为什么要再次这样做。检查此屏幕截图一次 demo