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

pkln4tw6  于 2022-11-22  发布在  React
关注(0)|答案(1)|浏览(171)

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

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

l0oc07j2

l0oc07j21#

根据文档,第一个参数是data or errors对象,第二个参数是form event
((数据:对象,e?:事件)=〉无效,(错误:对象,e?:事件)=〉无效)=〉函数
在你的例子中,e是数据,这就是为什么你得到的e.preventDefault不是函数错误。
这样试试

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

相关问题