reactjs 我无法使用FileReader预览图像

li9yvcax  于 2023-01-12  发布在  React
关注(0)|答案(1)|浏览(160)

我在reactjs中使用filereader时遇到了问题,实际上我想在加载后预览图像,但状态管理器没有更改,图像也没有加载

import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { isEmpty } from "../../Components/Utils";
import Img from "../../styles/assets/icons/img.svg";
import { createProduct } from "../../actions/product.action";
const AddProduct = () => {
  const [productText, setProductText] = useState("");
  const [productFile, setProductFile] = useState();
  const [productPrice, setProductPrice] = useState(0);
  const [productImg, setProductImg] = useState("");
  const [isDownload, setIsDownload] = useState(false);
  const [preview, setPreview] = useState("");

  const categories = useSelector((state) => state.categoriesReducer);

  const dispatch = useDispatch();

  const handlePreviewImg = (e) => {
    const reader = new FileReader();

    reader.onLoad = () => {
      if (reader.readyState === 2) {
        setPreview(reader.result);
        setIsDownload(true);
      }
    };

    reader.readAsDataURL(e.target.files[0]);
    setProductFile(e.target.files[0]);
  };

然后我尝试在输入文件标记中记录,以便可以考虑上载

<div className="dashboard__categories__form__picture add__product__picture">
            <input
              type="file"
              name="product"
              id="file"
              accept=".jpg, .jpeg, .png"
              className="inputfile"
              onChange={handlePreviewImg}
            />
            <label htmlFor="file">
              {!isDownload ? (
                <img src={Img} alt="icons" />
              ) : (
                <img src={preview} alt="categorie-pic" />
              )}
            </label>
          </div>

出什么事了?请帮帮忙

jgzswidk

jgzswidk1#

我相信您不需要使用FileReader
也许您可以使用URL.createObjectURL

const handlePreviewImg = (e) => {
  const blobUrl = URL.createObjectURL(e.target.files[0]);
  setPreview(blobUrl);
}

createObjectURL可能导致内存泄漏,因此您应该阅读该文档。

相关问题