首页 > 解决方案 > 如何将我的集合中的文档放入一个对象数组中,这些对象的字段来自 Google Firestore?

问题描述

我正在创建一个 React 应用程序,它存储它的 Pokedex 条目,以及它在 Google Firestore 上的静态资产。

我有这样的设置:

图片

目标是检索这些 Pokemon 文档并将它们返回到类似于我可以在本地执行的对象数组中。我能够取回条目的控制台日志,但我似乎无法在渲染过程中显示它们中的任何一个,我相信这是由于它们不在数组中。

 [{"index": "001", "name": "bulbasaur"},
  {"index": "002", "name": "ivysaur"},
  {"index": "003", "name": "venesaur"},
  {"index": "004", "name": "charmander"},
  {"index": "005", "name": "charmeleon"},
  {"index": "006", "name": "charizard"},
  {"index": "007", "name": "squirtle"},
  {"index": "008", "name": "wartortle"},
  {"index": "009", "name": "blastoise"},
  {"index": "010", "name": "caterpie"},
  {"index": "011", "name": "metapod"},
  {"index": "012", "name": "butterfree"},
  {"index": "013", "name": "weedle"},
  {"index": "014", "name": "kakuna"},
  {"index": "015", "name": "beedrill"}]

是我的输出。我的代码看起来像这样从“pokedex”集合中检索文档。我希望能够执行一个函数来使用单独条目列出这些条目,这些条目可以使用它们的字段(如索引号和名称)显示,如输出中所示,但是当我使用时我无法在渲染过程中访问它例如“this.state.pokemon[0]”。

state = {
    pokemon: null
}

componentDidMount() {
    db.collection('pokedex')
    .get()
    .then( snapshot => {
        const testList = []
        snapshot.forEach(doc => {
            const data = doc.data();
            testList.push(data);
        })
        this.setState({pokemon: testList})
        console.log(this.state.pokemon)
    })
    .catch (error => console.log(error))
}

谢谢

标签: javascriptreactjsgoogle-cloud-firestore

解决方案


尝试下面的代码更新(假设您使用的是 React 类组件),包括将初始 pokemon 状态设置为空数组。您需要明确说明要提取哪些文档字段(即,您需要将“ name”、“ element”、“ HP”替换为您自己的字段)

constructor() {
      super();
      this.state = {
         pokemon: [],
      };
   }

   componentDidMount() {
      this.unsubscribe = db.collection('pokedex').onSnapshot(this.getCollection);
   }

   componentWillUnmount() {
      this.unsubscribe();
   }

   getCollection = querySnapshot => {
      const testList = [];
      querySnapshot.forEach(res => {
         const { name, element, HP } = res.data();
         testList.push({
            key: res.id,
            res,
            name,
            element,
            HP
         });
      });
      this.setState({
         pokemon: testList
      });
   };


推荐阅读