在我的相机组件中,我想每 3 张照片将照片上传到存储桶。我在 React 中使用状态将图像 blob 保存到数组中。前 3 张照片一切正常,但之后,我无法将数组重置为空,并且看似随机数量的照片被上传到我的存储桶中。
let [blobs, setBlobs] = useState([]);
const capturePhoto = async () => {
const photo = await camera.current.takePhoto();
fetch(photo.path)
.then(res => {
setBlobs([...blobs, res._bodyBlob]);
console.log('blobs', blobs.length, blobs);
})
.catch(err => {
console.log('err', err);
});
checkLength();
};
const checkLength = async () => {
if (blobs.length >= 2) {
// upload files to a folder with the current date in a firebase cloud bucket
const datestring = new Date().toLocaleString('de-DE');
blobs.forEach((blob, i) => {
uploadFile(blob, datestring + '/' + (i + 1) + '.jpg');
});
// reset state
setBlobs([]);
sendNotification('Photos uploaded');
toggleDialog();
}
};
我通过控制台记录了我的数组,并且大小只会增加。另外,它从零开始控制台日志记录,尽管我已经添加了一个元素,这可能是因为 setState() 是异步的。
我试图通过将其包装在承诺中来等待重置,但遗憾的是这也不起作用。
一旦有 3 个 Blob,如何将其上传到云端并在之后重置列表?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
因此,这确实取决于代码的执行方式,特别是 setState 的异步性质,因此您可以使用 setState 的回调形式。这是一个例子:
这是包含其余代码的完整示例:
const capturePhoto = async () => { const photo = await camera.current.takePhoto(); fetch(photo.path) .then(res => { setBlobs(prevBlobs => [...prevBlobs, res._bodyBlob]); console.log('blobs', blobs.length, blobs); }) .catch(err => { console.log('err', err); }); checkLength(); }; const checkLength = async () => { if (blobs.length >= 2) { // upload files to a folder with the current date in a firebase cloud bucket const datestring = new Date().toLocaleString('de-DE'); blobs.forEach((blob, i) => { uploadFile(blob, datestring + '/' + (i + 1) + '.jpg'); }); // reset state setBlobs([]); sendNotification('Photos uploaded'); toggleDialog(); } };