Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

reactjs - Reset file upload after useState react js hooks

I wanted to reset my file upload control after I add selected image to array with useState hooks, but it is not somehow working for me.

My Code -

const fileInputRef = useRef();
const[images,setImages]=useState([]);

const addImage = (e)=>{
 setImages([...images,e.target.files])
}


useEffect(()=>{
if(fileInputRef) fileInputRef.current.value=null
 },[images])

return( <input type="file" ref={fileInputRef} onChange={addImage} />)

Now here fileInputRef is reset, but the problem here is I am getting images array with FileList object as length 0 as shown in the image below

enter image description here.

Please help.

question from:https://stackoverflow.com/questions/65626134/reset-file-upload-after-usestate-react-js-hooks

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

the problem is that you are not passing a copy of the file it's a reference e.target.files all you need is to spread it so you copy it so when useEffect run and delete the reference you have a copy in the images state

import React, { useEffect, useState, useRef } from "react";

const Stack = () => {
  const fileInputRef = useRef();
  const [images, setImages] = useState([]);

  const addImage = (e) => {
    setImages([...images, ...e.target.files]);
  };

  useEffect(() => {
    if (fileInputRef) fileInputRef.current.value = null;
  }, [images]);

  console.log(images);
  return <input type="file" ref={fileInputRef} onChange={addImage} />;
};

export default Stack;

i add a demo on codesandbox here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...