【问题标题】:Firebase error: Function CollectionReference.doc() cannot be called with an empty pathFirebase 错误:无法使用空路径调用函数 CollectionReference.doc()
【发布时间】:2021-04-10 03:05:32
【问题描述】:

我目前有一个错误,我不知道为什么。该错误仅在我重新加载产品页面时发生,然后我在下面的 img 中收到错误。该页面仍然加载所有产品,所以我不知道发生了什么。我认为它与 props.Cat 有关,它只包含一个字符串,其中包含从我的 app.jsx 传递的类别名称

import React from "react";
import { useEffect, useState } from "react";
import { firestore } from "../../../FireBase/FireBase";
import Button from "../../Elements/Button/Button";
import "./Products2.scss";

const Product = (props) => {
  const [ProductList, setProductList] = useState([]);
  const [cartList, setCart] = useState(null);

  useEffect(() => {
    const fetchCart = async () => {
      const doc = await firestore.collection("Users").doc(props.id).get();
      const data = doc.data();
      if (data === []) {
        setCart(null);
      } else {
        setCart(data.cart);
      }
    };

    fetchCart();
  }, [props]);

  const getProduct = async () => {
    if (props.Cat) {
      try {
        var list = [];
        var snapshot = await firestore.collection(props.Cat).get();
        snapshot.forEach((doc) => {
          list.push(doc.data());
        });
        setProductList([...list]);
      } catch (e) {
        alert(e);
      }
    }
    else{
      return <h1>Loading...</h1>;
    }
  };

  useEffect(() => {
    getProduct();
  },);

  const addCart = async (name, img, price) => {
    try {
      var quanChangeAt = null;
      var item = {
        id: name,
        Name: name,
        Img: img,
        Quan: 1,
        price: price,
      };
      if (cartList === null) {
        alert("Please Login first");
        return;
      }
      for (let i = 0; i < cartList.length; i++) {
        if (cartList[i].Name === item.Name) {
          quanChangeAt = i;
        }
      }
      if (quanChangeAt !== null) {
        item.Quan = cartList[quanChangeAt].Quan + 1;
        cartList[quanChangeAt] = item;
        await firestore.collection("Users").doc(props.id).update({
          cart: cartList,
        });
      } else {
        cartList.push(item);
        await firestore.collection("Users").doc(props.id).update({
          cart: cartList,
        });
      }
      alert(name + " added to cart succefully");
      console.log("added cart", cartList);
    } catch (error) {
      alert(error);
    }
  };

  if (!ProductList) {
    // You can render a placeholder if you like during the load, or just return null to render nothing.
    return <h1>Loading...</h1>;
  }

  return (
    <div className="ProductLayout">
      <h1>{props.Cat}</h1>
      <div className="products">
        {ProductList.map((listItem) => (
          <div className="item" key={listItem.Name}>
            <h2>{listItem.Name}</h2>
            <img src={listItem.img} alt={listItem.Name} />
            <h5>Description</h5>
            <p>{listItem.Description}</p>
            <br />
            <h5>Envirmental Benifit</h5>
            <p>{listItem.EvntBenefit}</p>
            <br />
            <h5>Price</h5>
            <p>$ {listItem.price}</p>
            <Button
              onClick={() =>
                addCart(listItem.Name, listItem.img, listItem.price)
              }
            >
              Add to cart
            </Button>
          </div>
        ))}
      </div>
    </div>
  );
};

export default Product;

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore


    【解决方案1】:

    根据堆栈跟踪,props.id 似乎未设置。崩溃前要调用的最后一个函数是 fetchCart()

    您可以通过将console.log(`##### props.id: ${props.id}`) 添加到fetchCart() 的第一行来轻松验证这一点。结果可能会打印出nullundefined

    【讨论】:

    • 你是对的。添加该语句时,id 出来为空,然后在加载后出现正确的 id。首先,我想问一下您是如何阅读该堆栈跟踪以找到崩溃的位置的?其次,您认为我如何解决这个问题并让程序等到 id 不为空?
    • 我找到了解决方案并编辑了问题以获得解决方案,但我仍然想知道您如何阅读该错误以找到它发生的位置。
    • 在 Javascript 中,堆栈跟踪会在顶部打印导致特定错误的函数,并且向下的每一层都是调用其上一层的函数。看你的,前几行是系统函数,第 5 行是你的,fetchCart。就知道它为 null 而言,错误消息 CollectionReference.doc() cannot be called with an empty path 暗示路径为空,因此您要么传递 null 要么传递一个文字空字符串(那个似乎不太可能)
    猜你喜欢
    • 2021-03-25
    • 2020-12-06
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 2016-10-04
    相关资源
    最近更新 更多