Unable to select uploaded files for tagging in React
P粉312631645
P粉312631645 2023-08-15 20:43:24
0
2
501
<p>I'm using React to create a file upload. I want the status variable to be set to the uploaded file (.docx or .pdf) as soon as the file is uploaded. But when calling set state, it shows up as undefined. </p> <pre class="brush:php;toolbar:false;">const [selectedFile, setSelectedFile] = useState(null) <Input type="file" onChange={handleImageUpload} accept={config.type}/> const handleImageUpload = (event: { target: { files: any[] } }) => { const file = event.target.files[0] if (file) { if (file.size > config?.fileSize) { setErrorMessage(config.fileSizeError) } else if (file?.name.endsWith(config.type)) { setSelectedFile(file) } else { reader.readAsDataURL(file) } } }</pre> <p>Once <code>setSelectedFile(file)</code> occurs, it shows <code>selectedFile</code> as undefined. Is this a specific reason why it happened? </p>
P粉312631645
P粉312631645

reply all(2)
P粉523335026

This is because when you call or log it in the console, your status has not been updated. You can log your status in the useEffect hook to view it when updated. Here is an example:

useEffect(() => {
    console.log("文件 >> ", selectedFile);
  }, [selectedFile]);
P粉760675452

I think your code works as expected, but when you try to call it, the state hasn't been updated yet.

According to React official documentation:

set函数只会更新下一次渲染的状态变量。
如果在调用set函数之后读取状态变量,你仍然会得到在调用之前屏幕上的旧值。

Now, this is my guess, but you can try adding this code:

setSelectedFile(file)

setTimeout(() => {
    console.log(selectedFile); 
}, 5000);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template