亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Unable to select uploaded files for tagging in React
P粉312631645
P粉312631645 2023-08-15 20:43:24
0
2
651
<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函數(shù)只會更新下一次渲染的狀態(tài)變量。
如果在調(diào)用set函數(shù)之后讀取狀態(tài)變量,你仍然會得到在調(diào)用之前屏幕上的舊值。

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