微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 React-Hook-Form 和 YupResolver 时遇到此错误:尝试导入错误:'set' 未从 'react-hook-form' 导出导入为 'o'

如何解决使用 React-Hook-Form 和 YupResolver 时遇到此错误:尝试导入错误:'set' 未从 'react-hook-form' 导出导入为 '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 中获取它们。

此代码经过测试且有效 - 请参阅此处的链接 - 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"),"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(),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 版本 7 文档调整了实现: https://react-hook-form.com/api/useform

现在它可以正常工作了。

,

我在使用 react-hook-form v6.16.5 和 @hookform/resolvers v2.5.2 时遇到了这个问题

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?