【问题标题】:Fetch data from firebase and initialise it in the useState before its mounted从 firebase 获取数据并在挂载之前在 useState 中初始化它
【发布时间】:2022-11-30 16:32:30
【问题描述】:

我是一个尝试从 firebase 获取对象的反应初学者,我想用从数据库获取的数据初始化 useState,但每次数据呈现未定义的值。这是我截断的代码

const ProductDetails = () => {
  const [tab, setTab] = useState("desc");
  const [products, setProducts] = useState([]);
  const reviewUser = useRef("");
  const reviewMsg = useRef("");
  const dispatch = useDispatch();
  const [rating, setRating] = useState(null);
  const { id } = useParams();
  const product = products.find(
    async (item) => (await item.key.slice(1)) === id
  );

const {
    image: imgUrl,
    title: productName,
    amount: price,
    description,
    shortDesc,
    category,
  } = product.data;

const fetchProducts = async () => {
    const db = getDatabase();
    const thumbnailRef = ref(db, "Contents/");

    onValue(thumbnailRef, (snapshot) => {
      snapshot.forEach((childSnapshot) => {
        const childData = childSnapshot.val();
        const childKey = childSnapshot.key;
        setProducts((prev) => [...prev, { key: childKey, data: childData }]);
      });
    });
  };

 useEffect(() => {
    fetchProducts();
  }, []);

我得到的错误是“无法读取未定义的属性(读取'数据')”。正如我所说,我是一个初学者,可能是我犯了一个业余错误,

【问题讨论】:

    标签: reactjs firebase


    【解决方案1】:

    product 函数中不应该有 async await

    【讨论】:

      【解决方案2】:

      首先,您不必在查找中使用 async/await。也将它包裹在 useMemo 周围,以便仅在 products 更改时执行。

        const product = useMemo(() => products.find(
           (item) =>  item.key === id
        ), [products]);
      

      其次,产品价值可能会以未定义的价值结束。所以需要处理。

      const {
          image: imgUrl,
          title: productName,
          amount: price,
          description,
          shortDesc,
          category,
        } = product?.data ||  { image: '',title: '',amount: '',description: '',shortDesc: '',category: '',};
      

      【讨论】:

        猜你喜欢
        • 2021-10-10
        • 2021-08-17
        • 2012-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-18
        • 2021-05-20
        相关资源
        最近更新 更多