我有一个钩子组件,允许用户上传一组图像。我想以这样的方式设置它,当组件未安装时,所有文件都上传到我的后端。
当前使用 useEffect
并返回一个函数作为 componentWillUnmount 替代品,但是当该函数被调用时,它需要的状态(上传的文件集)为空,即空列表。有没有办法解决这个问题或有更好的方法来做到这一点?我怀疑是因为 stagedUploadedImages
的 useState 设置为空列表。 不能从该组件中解除状态。
const [stagedUploadedImages, setStagedUploadedImages] = useState([]);
const uploadStagedFiles = () => {
// when this is reached by the useEffect method `stagedUPloadedImages` is empty list
stagedUploadedImages.forEach((file) => {
const formData = new FormData();
formData.append("files", file);
api.uploads.uploadWithNoAssociation(formData).then((response) => {
console.log("ImageGallery: response: ", response);
});
});
};
useEffect(() => {
return () => {
uploadStagedFiles();
};
}, []);
const handleUpload = (files) => {
setStagedUploadedImages([...files]);
};
答案 0 :(得分:1)
const [stagedUploadedImages, setStagedUploadedImages] = useState([]);
const valueRef = useRef();
const uploadStagedFiles = () => {
valueRef.current.forEach((file) => {
const formData = new FormData();
formData.append("files", file);
api.uploads.uploadWithNoAssociation(formData).then((response) => {
console.log("ImageGallery: response: ", response);
});
});
};
useEffect(() => {
valueRef.current = stagedUploadedImages;
}, [stagedUploadedImages]);
useEffect(() => {
return () => {
uploadStagedFiles();
};
}, []);