I'm trying to convert my class-based React component to a functional component. How should I convert functions like:
onFileUpload = async () => {
const formData = new FormData();
formData.append(
"ImageData.File",
this.state.selectedFile,
this.state.selectedFile.name
);
fetch('/api/Image', {
method: 'POST',
body: formData
}).then(resposne => resposne.json())
.then(data => {
console.log(data);
this.setState({ uploadResult: "File " + data.fileName + " successfully uploaded." });
this.getList();
});
};
The whole code comes here: https://drive.google.com/file/d/1YSSMTGkxzeH1R1V2rgQkwl1QwxnoXtuq/view?usp=sharing
const FuncComponent = () => {
const onFileUpload = async () => {
// do magic here
}
return <div />
}
You are going to replace this.state.selectedFile
with:
const [selectedFile, setSelectedFile] = useState() // and pass useState the initial state
When you need to update selectedFile
you will call setSelectedFile()
with the new data.
This is the same for uploadResult
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.