【问题标题】:Can't get data from firestore by Id on my ProductDetail page无法在我的 ProductDetail 页面上按 Id 从 Firestore 获取数据
【发布时间】:2021-08-09 22:08:46
【问题描述】:

我为 ProductDetail 页面创建了一个动态路由(每个 Restaurant 都有自己的详细信息,应显示在此页面上)。路由正在运行,但我没有得到任何数据,而且我无法通过每家餐厅的 Id 找出从 Firestore 获取数据的正确方法。

更新:

现在产品详细信息正在控制台中呈现,但问题仍然是如何在我的详细信息页面中返回它们

更新!! : ProductDetail.js

import { useParams, useRouteMatch } from "react-router-dom";
import { firestore } from "../../../../../fire";

function ProductDetail() {
  const { productId }= useParams();

  const [product, setProduct] = useState();

  useEffect( () =>  {
 
   firestore
     .collection("Restaurants")
     .doc(productId).get()
     .then( doc => {
       console.log(doc.data())
       setProduct(doc.data());
     })
   }, () => {

 }
 );
 
  return (
    <div className="col-12">
      <div className="card">
        <h1>{productId.name_restaurant} </h1>
        <p>Price:${productId.Currency}</p>
        <p>{productId.email} </p>
      </div>
    </div>
  );
  }
export default ProductDetail;   

这是我的控制台:返回餐厅的所有详细信息

仍然无法在我的页面上返回详细信息

【问题讨论】:

    标签: javascript reactjs google-cloud-firestore


    【解决方案1】:
    import React, {useEffect, useState} from "react";
    import { useRouteMatch } from "react-router-dom";
    
    function ProductDetail() {
      const { params: {productId} }= useRouteMatch("/react/ecom-product-detail/:productId");
      const [product, setProduct] = useState(null);
    
      useEffect(() => {
        firestore
          .collection("Restaurants")
          .doc(productId)
          .get()
          .then((snap) => setProduct(snap.data()));
      }, []);
    
      return (
        <div className="col-12">
          <div className="card">
            <h1>{product.name_restaurant}</h1>
            <p>Price:${product.Currency}</p>
            <p>{product.email} </p>
          </div>
        </div>
      );
    }
    
    export default ProductDetail;   
    

    【讨论】:

    • 我在第 6 行收到此错误:TypeError: Cannot read property 'params' of null
    • @HoudaBoukhobza 你能用“const match = ...”、“console.log(match)”替换“const { params: {productId} } = ...”并发布结果吗在这里?
    • 错误:TypeError:无法读取 null 的属性“name_restaurant”
    • @HoudaBoukhobza 是的,只需在函数中注释除 "const match = useRouteMatch("/react/ecom-product-detail/:productId"); console.log(match)" 之外的所有内容
    • 我已经更新了问题,因为现在产品详细信息正在控制台中呈现,但问题仍然是如何在我的详细信息页面中返回它们
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2021-08-15
    • 2023-03-15
    相关资源
    最近更新 更多