React-我的表单正在提交空数据,因为已声明但从未使用过"e"和"data"? [英] React - My form is submitting empty data because 'e' and 'data' are declared but never used?

查看:59
本文介绍了React-我的表单正在提交空数据,因为已声明但从未使用过"e"和"data"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 react-hook-form 来实现表单.我实际上无法正确连接数据和事件.docs指出,我正在使用react-hook-form库中的 handleSubmit 函数,并将我的自定义Axios帖子作为 onSubmit 参数:{handleSubmit(onSubmit)

I'm trying to implement a form using react-hook-form. I'm not able to actually connect the data and event working correctly. As the docs state, I'm using the handleSubmit function from the react-hook-form library, with my custom Axios post as the onSubmit parameter: onSubmit={handleSubmit(onSubmit)

根据我的Vscode,数据和事件未正确注册. const onSubmit =(data,e)=>{} .

According to my Vscode, the data and event are not registering correctly const onSubmit = (data, e) => {}.

提交表单后,Web控制台将记录一个空表单: {email:",密码:''"}

When the form is submitted, the web console logs an empty form: {email: "", password: ""}

我的代码在做什么错?为简洁起见,请注意,我删除了下面的密码文本字段.

What am I doing wrong with my code? Note for sake of brevity, I removed the password textfield below.

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 onSubmit = (data, e) => {
            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(onSubmit)}>
                    <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>

如何正确链接所有内容并获取输入数据和事件以与表单中的 onSubmit = {handleSubmit(onSubmit)进行通信?

How can I link up everything correctly and get my input data and event to communicate with the onSubmit={handleSubmit(onSubmit) inside my form?

谢谢您的帮助!

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,
          ...e
        });
      };

    const dispatch = useDispatch();
    
    const onSubmit = (data, e) => {
            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,
                    }))
                })
        
        };


    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(onSubmit)}>
                    <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={
                                        (evt) => {
                                          let key = evt.currentTarget.name;
                                          let value = evt.currentTarget.value;
                                          handleChange({[key]: value});
                                        }
                                      }
                                    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>
                    <TextField
                        variant="outlined"
                        margin="normal"
                        inputRef={register}
                        required
                        fullWidth
                        name="password"
                        label="Password"
                        type="password"
                        id="password"
                        autoComplete="current-password"
                        onChange={
                            (evt) => {
                              let key = evt.currentTarget.name;
                              let value = evt.currentTarget.value;
                              handleChange({[key]: value});
                            }
                          }
                    />

推荐答案

为什么不使用 onSubmit 函数上的 data 参数?

Why not use the data parameter on the onSubmit function?

const onSubmit = (data, e) => {
        console.log(data);
    
        axiosInstance
            .post(`auth/token/`, {
                grant_type: 'password',
                username: data.email,
                password: data.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: data.email,
                    password: data.password,
                    loggedIn: true,
                }))
            })
    
    };

form

  <Controller
    as={
      <TextField
        variant="outlined"
        margin="normal"
        fullWidth
        label="Email Address"
        autoComplete="email"
        autoFocus
        error={Boolean(fieldsErrors.email)}
      />
    }
    name="email"
    control={control}
    rules={{
      required: 'Required',
      pattern: {
      value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
      message: 'invalid email address'
      }
    }}
    defaultValue=""
  />
  {fieldsErrors.email?.type && <p>{fieldsErrors.email?.message}</p>}

这篇关于React-我的表单正在提交空数据,因为已声明但从未使用过"e"和"data"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆