【问题标题】:React - Unhandled Rejection (TypeError): e.preventDefault is not a functionReact - 未处理的拒绝(TypeError):e.preventDefault 不是函数
【发布时间】:2021-02-02 01:37:51
【问题描述】:

当我尝试使用 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>
    );
}

感谢您提供有关如何解决原始错误的任何帮助或指导!

【问题讨论】:

    标签: javascript reactjs material-ui react-hook-form


    【解决方案1】:

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

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

    在您的情况下,e 是数据,这就是为什么您会收到 e.preventDefault is not a function error。

    这样试试

     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

    【讨论】:

    • 您好,Naren,感谢您的帮助。所以我从handleSubmitAxios 函数中删除了e.PreventDefault。我确实添加了您添加数据作为第一个参数的建议。但是,现在当我按下提交时,我正在发送一个空的 JSON,其中没有 email 字段的值。鉴于我上面的代码,你知道我怎样才能让data 参数正常工作吗?
    • 我将此主题移至新的 stackoverflow 问题,因为您已经从这篇文章中回答了我的原始问题,请在此处查看我的新帖子 :):stackoverflow.com/questions/66003394/…
    猜你喜欢
    • 1970-01-01
    • 2018-12-09
    • 2021-10-14
    • 2020-11-16
    • 2020-05-06
    • 2019-10-27
    • 2020-09-26
    • 2021-04-16
    • 2021-03-09
    相关资源
    最近更新 更多