通过getDownloadURL和State (productThumbnail)设置向Firebase提交包含多个图像



进入开发工具的调试器显示两个问题:

  1. 无法读取未定义的property .then

  2. 它还显示两个文件被"放置"到存储2个单独的实例,我认为这导致调度addProductStart也运行两次。移动setProductThumbnail((prevState)…一行删除了.then undefined错误,但也导致addProductStart运行两次。导致制作2个产品而不是1个产品,其中包含多个图像。

所以要解决这个问题,handlessubmit函数需要重构到getDownloadURL能够将2个url放到一个数组中,并设置为State productThumbnail,以便产品可以与附加在firestorecollection中的多个图像一起上传

const productImgHandler = (e) => {
for (var i = 0; i < e.target.files.length; i++) {
const selectedFiles = e.target.files[i];
selectedFiles["id"] = Math.random();
setpreProductThumbnail((prevState) => [
...prevState,
selectedFiles,
]);
console.log(selectedFiles);
}
};
const handleSubmit = (e) => {
const promises = [];
e.preventDefault();
preproductThumbnail.map((image) => {
promises.push(storage().ref(`prodimages/${image.name}`).put(image));
storage()
.ref(`prodimages/${image.name}`)
.put(image)
.on(
"state_changed",
(snapshot) => {
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) *
100;
console.log(progress);
},
(err) => {
setError(err.message);
},

() => {
storage()
.ref("prodimages")
.child(image.name)
.getDownloadURL()
setProductThumbnail((prevState) => [...prevState, productThumbnail])
.then((productThumbnail) => { // put an array in here, then change fetch function on Productpage
console.log("PRODTHUMB2", productThumbnail);
dispatch(
addProductStart({
productCategory,
productName,
productThumbnail,
productPrice,
productDesc,
})
);
}, resetForm());
}
);
});```

setProductThumbnail不返回承诺到.then()承诺链上。您应该在.then()语句中处理setProductThumbnail

最新更新