简体   繁体   中英

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

I'm creating a React app that is storing it's Pokedex entries, along with its static assets on Google Firestore.

I have it setup like this:

图片

The goal is to retrieve these documents that are Pokemon and return them in an array of objects similar to what I can do locally. I am able to get console logs of the entries back, but I can't seem to display any of them in the rendering process and I believe it's due to them not being in an array.

 [{"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"}]

Is my output. My code is looking like this to retrieve the documents from the "pokedex" collection. I want to be able to perform a function to list these out using solo entries that can be displayed using their fields such as index number and name as shown above in the output, but I can't access it in the rendering process when I use "this.state.pokemon[0]" for example.

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))
}

Thank you

Try the code update below (assuming you're using a React class component), including setting the initial pokemon state to an empty array. You will need to be explicit about which document fields you want to pull in (ie, you'll need to replace " name ", " element ", " HP " with your own fields)

 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 }); };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM