Faced this error while using React-Hook-Form and YupResolver: Attempted import error: 'set' is not exported from 'react-hook-form' (imported as 'o')

Faced this error while using React-Hook-Form and YupResolver: Attempted import error: 'set' is not exported from 'react-hook-form' (imported as 'o')

我正在使用 Capacitor、Ionic、React 开发应用程序,最近我在第一次使用 React Hook Form 和 YupResolver 时遇到以下错误:

当我尝试 运行 项目时,出现此错误:

Failed to compile
./node_modules/@hookform/resolvers/dist/resolvers.module.js
Attempted import error: 'set' is not exported from 'react-hook-form' (imported as 'o').

我想创建并验证用于更改密码的表单,将新密码提交给外部 API /change-password。表格将如下所示:

Actual Password: ...
New Password: ...
Confirm new Password: ...

Submit

组件:

import {
  IonContent,
  IonPage,
  IonItem,
  IonLabel,
  IonButton,
  IonInput,
  IonRow,
  IonAlert,
  IonGrid,
  IonCol,
} from "@ionic/react";
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import axios from "axios";

 // form validation rules
  const validationSchema = yup.object().shape({
    password: yup
      .string()
      .min(8, "Password must be at least 8 characters")
      .required("Password is required"),
    newPassword: yup
      .string()
      .min(8, "Password must be at least 8 characters")
      .required("New Password is required"),
    confirmPassword: yup
      .string()
      .oneOf([yup.ref("newPassword"), null], "Passwords must match")
      .required("Confirm Password is required"),
  });

const ChangePassword: React.FC = () => {

//get the actual password from React Contenxt
  const {
    password,
    setPassword,
    alertMessage,
    setAlertMessage,
  } = React.useContext(AuthContext);

  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState(""); 

  // functions to build form returned by useForm() hook
  const { register, handleSubmit, errors } = useForm({
    resolver: yupResolver(validationSchema),
  });

  const onSubmit = () => {
    const data = {
      oldPassword: password,
      newPassword: newPassword,
      sourceId: 1,
    };

    axios
      .post("change-password", data)
      .then((response) => {
        return response.data;
      });
  };

  return (
    <React.Fragment>
      <IonPage className="ion-page" id="main-content">
        <IonContent className="ion-padding">
          <IonGrid>  
            <h3>Change Password</h3>

            <form onSubmit={handleSubmit(onSubmit)}>
              <IonItem>
                <IonLabel position="floating">Actual Password</IonLabel>
                <IonInput
                  name="password"
                  type="password"
                  value={password}
                  ref={register}
                  className={`form-control ${
                    errors.password ? "is-invalid" : ""
                  }`}
                  onIonChange={(e) => setPassword(e.detail.value!)}
                ></IonInput>
                <div className="invalid-feedback">
                  {errors.password?.message}
                </div>
              </IonItem>

              <IonItem>
                <IonLabel position="floating">New Password</IonLabel>
                <IonInput
                  name="newPassword"
                  type="password"
                  value={newPassword}
                  ref={register}
                  className={`form-control ${
                    errors.newPassword ? "is-invalid" : ""
                  }`}
                  onIonChange={(e) => setNewPassword(e.detail.value!)}
                ></IonInput>
                <div className="invalid-feedback">
                  {errors.newPassword?.message}
                </div>
              </IonItem>

              <IonItem>
                <IonLabel position="floating">
                  Cofirm New Password
                </IonLabel>
                <IonInput
                  name="confirmPassword"
                  type="password"
                  value={confirmPassword}
                  ref={register}
                  className={`form-control ${
                    errors.confirmPassword ? "is-invalid" : ""
                  }`}
                  onIonChange={(e) => setConfirmPassword(e.detail.value!)}
                ></IonInput>
                <div className="invalid-feedback">
                  {errors.confirmPassword?.message}
                </div>
              </IonItem>

              <IonButton type="submit">
                Submit
              </IonButton>
            </form>
          </IonGrid>
        </IonContent>
      </IonPage>
    </React.Fragment>
  );
};

export default ChangePassword;
@hookform/resolvers@2.4.0
yup@0.32.9
react-hook-form@6.15.6

任何帮助将不胜感激。谢谢!

react-hook-form 改变了做事的方式。此外,您不需要自己跟踪这些值,您可以从 react-hook-form 中获取它们。

此代码已经过测试并且有效 - 请参阅此处 link - https://codesandbox.io/s/react-hook-form-fieldsarray-yup-validation-min-length-forked-rccmg?file=/src/index.js:0-1934

import React from "react";
import ReactDOM from "react-dom";
import { useForm, useFieldArray } from "react-hook-form";
import { object, ref, string } from "yup";
import { yupResolver } from "@hookform/resolvers";
// import "./styles.css";
import "@ionic/react/css/core.css";

import {
  IonContent,
  IonPage,
  IonItem,
  IonLabel,
  IonButton,
  IonInput
} from "@ionic/react";

const validationSchema = object().shape({
  password: string()
    .min(8, "Password must be at least 6 characters")
    .required("Password is required"),
  newPassword: string()
    .oneOf([ref("password"), null], "Passwords must match")
    .required("New Password is required"),
  confirmPassword: string()
    .oneOf([ref("newPassword"), null], "Passwords must match")
    .required("Confirm Password is required")
});

function App() {
  const { register, errors, handleSubmit, getValues } = useForm({
    mode: "onChange",
    resolver: yupResolver(validationSchema)
  });

  return (
    <IonPage>
      <IonContent>
        <form onSubmit={handleSubmit(console.log)}>
          <IonItem>
            <IonLabel>PASSWORD</IonLabel>
            <IonInput name="password" type="text" ref={register}></IonInput>
          </IonItem>

          <IonItem>
            <IonLabel>NEW PASSWORD</IonLabel>
            <IonInput name="newPassword" type="text" ref={register}></IonInput>
          </IonItem>

          <IonItem>
            <IonLabel>CONFIRM PASSWORD</IonLabel>
            <IonInput
              name="confirmPassword"
              type="text"
              ref={register}
            ></IonInput>
          </IonItem>

          <pre>Errors: {JSON.stringify(errors, null, 2)}</pre>
          <pre>Values: {JSON.stringify(getValues(), null, 2)}</pre>
          <input type="submit" />
        </form>
      </IonContent>
    </IonPage>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我没有找到专门针对此错误的解决方案。所以我决定继续实施并将 RHF 从 6.x.x 升级到最新版本 7.1.1,因为我也在使用最新版本的 Resolvers。 https://react-hook-form.com/migrate-v6-to-v7/ 我也根据RHF version 7的文档调整了实现: https://react-hook-form.com/api/useform

现在可以正常使用了。

我在使用 react-hook-form v6.16.5 和@hookform/resolvers v2.5.2

时遇到了这个问题

我将@hookform/resolvers 降级到 v1.3.7,现在可以使用了。

我的错误是我将导入实现为

import { yupResolver } from "@hookform/resolvers"; 而不是

import { yupResolver } from "@hookform/resolvers/yup";

将此留在此处,因为它可能会对某人有所帮助。

我正在使用 "react-hook-form": "^7.25.1" 版本并且我导入为

从“@hookform/resolvers”导入 { yupResolver}; 代替

您可以如下所示导入(它对我有用)

从'@hookform/resolvers/yup'导入{yupResolver};