从数组字段中的文档ID获取Firestore文档并在React中显示

问题描述 投票:0回答:1

我在Firestore上有2个集合,boxes包含字段shoes,它是对shoes collections的引用ID的数组:

enter image description hereenter image description here

我的盒子组件正在获取所有盒子并显示它们的编号。我还想在其中显示鞋子的属性,例如照片。所以我就这样:

Boxes.jsx

// DEPENDENCIES
import React, { useEffect, useContext } from 'react';

// COMPONENTS
import BoxCard from '../Components/BoxCard';

// CONTEXT
import ShoesContext from '../Contexts/ShoesContext';

// HELPERS
import db from '../config/firebase';

let initialBoxes = [];

const Boxes = () => {
  const { boxes, setBoxes } = useContext(ShoesContext);
  useEffect(() => {
    initialBoxes = [];
    db.collection('boxes')
      .get()
      .then(querySnapshot => {
        querySnapshot.forEach(doc => {
          initialBoxes.push(doc);
        });
        setBoxes(initialBoxes);
      });
  }, []);
  return (
    <div>
      <h3>You have {boxes.length} boxes:</h3>
      {!boxes ? (
        <div>Loading..</div>
      ) : (
        boxes.map(box => {
          return <BoxCard box={box} key={box.id} />;
        })
      )}
    </div>
  );
};

export default Boxes;

Boxes.jsx

import React from 'react';
import TestComponent from './TestComponent';

const BoxCard = ({ box }) => {
  const theBox = box.data();

  return (
    <div>
      <h5>
        Box number {theBox.number} has {theBox.shoes.length} shoes:{' '}
      </h5>
      {theBox.shoes.map(shoe => {
        return <TestComponent shoe={shoe} />;
      })}
    </div>
  );
};

export default BoxCard;

这就是所有中断的地方:

import React from 'react';

const TestComponent = ({ shoe }) => {
  useEffect(() => {
    let hell;
    shoe.get().then(doc => {
      hell = doc.data();
    });
  }, []);
  return <div>{hell ? hell.season : 'loading...'}</div>;
};

export default TestComponent;

hell未定义。我还没有找到渲染嵌套文档的方法,因此可以在TestComponent组件中使用它们。我到目前为止在网上进行的广泛研究尚未成功,因此今天是我的问题。

谢谢!

更新:

我似乎找到了答案,下面乔什的回答使我走上了正确的轨道。请参见下面的TestComponent.jsx代码:

import React, { useEffect, useState } from 'react';

// HELPERS
import db from '../config/firebase';

const TestComponent = ({ shoe }) => {
  
  const [hell, setHell] = useState();

  useEffect(() => {
    db.collection('shoes')
      .doc(shoe.id)
      .get()
      .then(doc => {
        setHell(doc.data());
      });
  }, []);

  return <div>{hell ? hell.season : 'loading...'}</div>;
};

export default TestComponent;
reactjs firebase google-cloud-firestore
1个回答
1
投票

[TestComponent中的shoe中的shoe.get()...是什么?不应该是db.doc(shoe).get()...

© www.soinside.com 2019 - 2024. All rights reserved.