在React Hook Form中获取更改前的字段值

问题描述 投票:0回答:1

我有

profile
组件,它从
context
获取一些值,然后根据用户交互对其进行编辑,当提交表单后触发功能
editProfile
时,我使用
isDirty
方法检查图像是否已更改,如果是这样,那么我将新图像
url
上传到
firebase
,但是我需要删除之前的图像,因为它已被更改,我怎样才能获得之前图像的值?


import { useContext } from "react";
import AuthContext from "../../context/Auth-context/AuthContext";
import { useForm } from "react-hook-form";
import useFilePreview from "../Helpers/useFilePreview";
import { post } from "../Helpers/post";
import { uploadImageToFirebase } from "../Helpers/uploadImageToFirebase";


function Profile() {

  const { user } = useContext(AuthContext);
  const form = useForm({
    defaultValues: {... , image: user?.image}
  });
  const { register, handleSubmit, watch, getValues, formState: { dirtyFields } } = form;
  const image = watch("image");
  const imageToDelete = getValues("image");
  const [imagePreview] = useFilePreview(image);

  const editProfile = async (data) => {

    let url;
    if (dirtyFields.image) {
      url = await uploadImageToFirebase(data.image[0]);
    }
    data.image = url || image;

    post(`http://localhost:8000/api/edit-profile/${data.id}`, "PUT", {...data});

  };


  return <form onSubmit={handleSubmit(editProfile)}>
          <img src={imagePreview} />
          <label>Change profile picture</label>
          <input {...register("image")} type="file" accept="image/*" />
          <button>Save changes</button>
        </form>


}

export default Profile;

我尝试定义一个常量并存储上一张图像,以便我可以删除它:

   const imageToDelete = getValues("image");

但这会给我新图像的值,因为

getValues("image")
也会改变,我需要一种方法在变脏之前捕获图像值,如何实现?预先感谢

reactjs react-hook-form
1个回答
0
投票

要跟踪 React 组件中之前的个人资料图像,请在组件安装时使用状态变量来存储初始图像 URL。这样,您以后需要删除旧图像时就可以引用它。

这是更新后的代码:

import { useContext, useEffect, useState } from "react";
import AuthContext from "../../context/Auth-context/AuthContext";
import { useForm } from "react-hook-form";
import useFilePreview from "../Helpers/useFilePreview";
import { post } from "../Helpers/post";
import { uploadImageToFirebase } from "../Helpers/uploadImageToFirebase";

function Profile() {
  const { user } = useContext(AuthContext);
  const [previousImage, setPreviousImage] = useState(user?.image);

  const form = useForm({
    defaultValues: { ... , image: user?.image }
  });
  const { register, handleSubmit, watch, formState: { dirtyFields } } = form;
  const image = watch("image");
  const [imagePreview] = useFilePreview(image);

  useEffect(() => {
    setPreviousImage(user?.image);
  }, [user]);

  const editProfile = async (data) => {
    let url;

    if (dirtyFields.image) {
      url = await uploadImageToFirebase(data.image[0]);
      if (previousImage) {
        // Call your function to delete the previous image from Firebase
        await deleteImageFromFirebase(previousImage);
      }
    }

    data.image = url || previousImage;
    await post(`http://localhost:8000/api/edit-profile/${data.id}`, "PUT", { ...data });
  };

  return (
    <form onSubmit={handleSubmit(editProfile)}>
      <img src={imagePreview} alt="Profile Preview" />
      <label>Change profile picture</label>
      <input {...register("image")} type="file" accept="image/*" />
      <button>Save changes</button>
    </form>
  );
}

export default Profile;
© www.soinside.com 2019 - 2024. All rights reserved.