【问题标题】:console.log isn't showing useState infoconsole.log 未显示 useState 信息
【发布时间】:2021-07-04 11:24:09
【问题描述】:

我将 Firestorage 与 React 一起使用。基本上我要做的是在用户将多张图片上传到 Firestore 之后,它会将图片的 URL 添加到 Firestore 数据库中,如图所示

但是,当我尝试将其添加到字段值中时,它什么也没显示。所以我继续使用 console.log(urls) 来查看我的代码有什么问题,并且在 console.log 中它没有显示数组中的任何内容。

这是我的代码:

const [productImages, setProductImages] = useState([])
const [urls, setUrls] = useState([])

function handleSubmit(e) {
    e.preventDefault()

    const promises = []
    setLoading(true)
    setError("")

    // PRODUCT IMAGE UPDATE IF NOT NULL
    if (productImages !== null) {
        const promises = []
        productImages.map((image) => {
            const uploadTask = storage.ref(`products_images/${image.name}`).put(image);
            promises.push(uploadTask)
            uploadTask.on(
            "state_changed",
            snapshot => {},
            error => {
                console.log(error);
            },
            async () => {
                await storage
                    .ref("products_images")
                    .child(image.name)
                    .getDownloadURL()
                    .then(urls => {
                        setUrls((prevState) => [...prevState, urls])
                    })
            }
            )
        })
        Promise.all(promises)
            .then(() => console.log("Images > ", urls))
            .catch((err) => console.log(err));
      }

    Promise.all(promises)
      .then(() => {
        //history.push("/")
        //TRIED PUTTING HERE AS WELL BUT IT'S STILL SHOWING NOTHING
      })
      .catch(() => {
        setError("Failed to update account")
      })
      .finally(() => {
        setLoading(false)
      })
  }

const handleChange = (e) => {
      for (let i=0; i<e.target.files.length; i++) {
          const newProductImages = e.target.files[i]
          newProductImages["id"] = Math.random();
          setProductImages((prevState) => [...prevState, newProductImages]);
      
    }
  }

在我的代码中,您可以看到我将console.log("Images &gt;", urls) 放在哪里。它什么都不返回,而是返回所有图像 URL。但是,当我将console.log("Images &gt;", urls) 放在所有函数的最后时,在 return() 之前它将显示所有 URL。我该怎么做才能让它在提交按钮上显示图像 URL?

---- 编辑----

我尝试使用 useEffect 将数据上传到 firestore 数据库,一旦它检测到 url 状态有一些东西,这实现了我想要的,但它是重复的。它检测到状态已经改变了两次,因为它有两个图像正在上传。有没有办法修复它,以便在状态存储多张图片后只上传一次?

useEffect(() => {
    if (urls.length) {
        const newProduct = {
            product_category: productCategoryRef.current.value,
            product_name: productNameRef.current.value,
            product_images: urls,
            product_postedby: currentUser.email
        }
        db.collection("products").add(newProduct);
    }
  },[urls])

【问题讨论】:

    标签: reactjs google-cloud-firestore firebase-storage


    【解决方案1】:

    我建议使用then()async/await,但不要在同一段代码中同时使用。虽然它们可以一起使用,但需要您更多地了解它们的功能。

    如果您使用put 返回的promise,代码会变得非常简单,然后将调用链接到getDownloadURL。据我所知,它变成了这样的:

    if (productImages !== null) {
        const promises = productImages.map((image) => {
            const ref = storage.ref(`products_images/${image.name}`);
            return ref.put(image))
                .then(() => ref.getDownloadURL());
        });
        Promise.all(promises).then((urls) => {
            setUrls(urls)
        })
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 2014-05-12
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 2011-03-15
      • 1970-01-01
      • 2021-07-24
      • 2020-03-12
      相关资源
      最近更新 更多