React - 我的表单正在提交空数据,因为 'e' 和 'data' 已声明但从未使用过?

React - My form is submitting empty data because 'e' and 'data' are declared but never used?

我正在尝试使用 react-hook-form 实现一个表单。我实际上无法正确连接数据和事件。正如文档所述,我正在使用 react-hook-form 库中的 handleSubmit 函数,并将我的自定义 Axios post 作为 onSubmit 参数: onSubmit={handleSubmit(onSubmit)

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

提交表单时,Web 控制台记录一个空表单: {email: "", password: ""}

我的代码哪里做错了?请注意,为了简洁起见,我删除了下面的密码文本字段。

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>

我怎样才能 link 正确设置所有内容并让我的输入数据和事件与我表单中的 onSubmit={handleSubmit(onSubmit) 通信?

感谢您的帮助!

编辑:

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 在其回调函数中只有一个参数,它是 event.. 您可以在其中使用 event.target 数组或 event.target.elements."fieldname" 获取数据(字段名是输入字段的name)或event.target.fieldname.value.....

提交:

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

嗯,只需删除 data 参数...

正在看

const handleChange = (e) => {
    updateFormData({
        ...formData,
    });
};

<TextField
...
onChange={handleChange}
...
/>

似乎 onChange 只是没有改变状态。你可能想要做这样的事情:

onChange={
  (evt) => {
    let key = evt.currentTarget.name;
    let value = evt.currentTarget.value;
    handleChange({[key]: value});
  }
}

然后

const handleChange = (e) => {
  updateFormData({
    ...formData,
    ...e
  });
};

如果“名称”属性是“密码”,这应该适用于密码字段。

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

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 组件
  <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>}