我正在研究以下代码。我期望console.log
将显示所选图像的URL。但它显示为空白。沙盒实现为here
import React, {useState} from 'react';
import FormControl from "@material-ui/core/FormControl";
import Button from "@material-ui/core/Button";
import Dialog from "@material-ui/core/Dialog";
import DialogTitle from "@material-ui/core/DialogTitle";
import './App.css';
function App() {
const [fileUrl, setFileUrl] = useState("");
const [file, setFile] = useState("");
const handleAudioChange = event => {
const selectedFile = event.target.files[0];
setFileUrl(URL.createObjectURL(event.target.files[0]));
console.log("fileUrl")
console.log(fileUrl)
setFile(selectedFile);
};
return (
<div>
<Dialog
open={true}>
<DialogTitle>Meme Generator Text</DialogTitle>
<FormControl >
<input
id="image"
required
type="file"
style={{visibility:"hidden"}}
accept="image/*"
onChange={handleAudioChange}
/>
<label htmlFor="image">
<Button
variant="outlined"
component="span"
>
Picture File
</Button>
</label>
</FormControl>
</Dialog>
</div>
);
}
export default App
答案 0 :(得分:1)
setSmth
函数异步运行。它触发重新渲染,然后useState
返回新值。
如果您立即需要值,则只需使用设置为状态的值即可:
const newFileUrl = URL.createObjectURL(event.target.files[0]);
setFileUrl(newFileUrl);
console.log("fileUrl");
console.log(newFileUrl);