Getting "InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable" when trying to update state variable onChange

Getting "InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable" when trying to update state variable onChange

美好的一天,我似乎无法弄清楚这一点。我收到“InvalidStateError:尝试使用一个不可用或不再可用的对象”让我解释一下:

我有一个 CustomUpload 组件:

export const CustomUpload = ({ name, children, accept, onChange, value }) => {
  const fileUpload = useRef(null);

  const handleClick = (e) => {
    e.preventDefault();
    fileUpload.current.click();
  };

  return (
    <div className="custom-upload-container">
      <label
        style={{ textAlign: "center", fontFamily: "var(--montserrat-text)" }}
        htmlFor={name}
      >
        {children}
      </label>
      <div className="custom-upload-input-container">
        <p>{value.name}</p>
        <div className="input-container">
          <input
            ref={fileUpload}
            className="custom-upload"
            type="file"
            name={name}
            accept={accept}
            onChange={onChange}
            value={value}
          />
        </div>

        <CustomButton onClick={handleClick}>Browse</CustomButton>
      </div>
    </div>
  );
};

然后我有一个页面,用户必须提交 5 张图片,但为了简单起见,我将使用两张:

export const Images = () => {
const [data, setData] = useState({
    image1: "",
    image2: "",
  });
const { image1, image2 } = data;

const handleOnChange = (value, fieldName) => {
setData({...data, [fieldName]: value });

return(
<form>
        <CustomUpload
          name="image1"
          onChange={(e) => handleOnChange(e.target.files[0], "image1")}
          value={image1}
          accept="image/*"
        >
          First Image
        </CustomUpload>
        <CustomUpload
          name="image2"
          onChange={(e) => handleOnChange(e.target.files[0], "image2")}
          value={image2}
          accept="image/*"
        >
          Second Image
        </CustomUpload>
</form>

}

问题是当我 select 图像时它给我错误,我似乎无法弄清楚我应该如何解决它。谢谢。

我明白了。所以问题是我正在使用 value prop 分配 CustomUpload 的值,这对于文本输入来说是正常的,但似乎会破坏文件输入。

<CustomUpload
          name="image1"
          onChange={(e) => handleOnChange(e.target.files[0], "image1")}
      >>> value={image1} //remove this line.
          accept="image/*"
        >
          First Image
</CustomUpload>

应该是:

<CustomUpload
          name="image1"
          onChange={(e) => handleOnChange(e.target.files[0], "image1")}
          accept="image/*"
        >
          First Image
</CustomUpload>

顺便说一句,这是处理多个文件上传并具有单个 onChangeHandler 和 useState 挂钩的非常巧妙的解决方案。希望这可以帮助人们:D