簡體   English   中英

如何將我的集合中的文檔放入一個對象數組中,這些對象的字段來自 Google Firestore?

[英]How do I put my Documents from my Collection into an array of objects with their own fields getting from Google Firestore?

我正在創建一個 React 應用程序,它在 Google Firestore 上存儲它的 Pokedex 條目以及它的 static 資產。

我有這樣的設置:

圖片

目標是檢索這些 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"}]

是我的 output。 我的代碼看起來像這樣從“pokedex”集合中檢索文檔。 我希望能夠執行 function 以使用單獨條目列出這些條目,這些條目可以使用索引號和名稱等字段顯示,如 output 中所示,但我在使用時無法在渲染過程中訪問它例如“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))
}

謝謝

嘗試下面的代碼更新(假設您使用的是 React class 組件),包括將初始口袋妖怪 state 設置為空數組。 您需要明確說明您想要提取哪些文檔字段(即,您需要將“ 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 }); };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM