[英]I am trying to pull data from firestore and set it to my array using the snapShot method
I am trying to set incoming data from firestore to an array in state.我正在尝试将来自 firestore 的传入数据设置为状态数组。 I am using the snapShot method to receive data changing events, and display users and updates but i only seem to receive only one document back.
我正在使用 snapShot 方法来接收数据更改事件,并显示用户和更新,但我似乎只收到一个文档。
import React, { Component } from 'react'
import firebase from '../firebase'
export class Display extends Component {
constructor(){
super();
this.state={
usersArr: []
}
}
componentDidMount(){
const db = firebase.firestore()
db.collection('users')
.onSnapshot(snap => {
let changes = snap.docChanges()
changes.forEach(change =>{
this.setState({usersArr: change.doc.data()})
})
})
}
When you do this,当你这样做时,
changes.forEach(change =>{
this.setState({usersArr: change.doc.data()})
})
Every time forEach
executes, it updates existing usersArr
from state and replaces it with latest one.每次
forEach
执行时,它usersArr
从 state 更新现有的usersArr
并将其替换为最新的。 So you end up with only last data in state.所以你最终只得到状态中的最后数据。
To get rid of this, you can use previous state
in setState
and concat
the new result to existing one.为了摆脱这一点,你可以使用
previous state
中setState
和concat
新的结果,以现有的一个。
changes.forEach(change =>{
this.setState(prevState=>({
...prevState,
usersArr : prevState.usersArr.concat(change.doc.data())
}), ()=>console.log(this.state.usersArr))
})
You may be getting multiple changes, but when you're looping over them and then set the state based on each individual document:您可能会得到多个更改,但是当您循环它们然后根据每个单独的文档设置状态时:
let changes = snap.docChanges()
changes.forEach(change =>{
this.setState({usersArr: change.doc.data()})
})
So the first iteration you're setting the state to the first changed document, the second iteration to the second document (overwriting the first), the third iteration to the third document (overwriting the second).因此,第一次迭代将状态设置为第一个更改的文档,第二次迭代设置为第二个文档(覆盖第一个),第三次迭代设置为第三个文档(覆盖第二个)。 So at the end of the loop, you only have the last document left in the state.
所以在循环结束时,您只剩下最后一个文档留在状态中。
If you want to set the data of all changed documents to the state, you'd do something like this:如果要将所有已更改文档的数据设置为状态,则可以执行以下操作:
let docs = []
let changes = snap.docChanges()
changes.forEach(change =>{
docs.push(change.doc.data())
})
this.setState({usersArr: docs})
The above only adds the changed documents to the state.以上仅将更改的文档添加到状态。 So initially that will be all documents, but when you later add a single document, the
docChanges()
will only contain that one document.所以最初这将是所有文档,但是当您稍后添加单个文档时,
docChanges()
将仅包含该文档。 It is more typical to add all documents to the state, which you do by iterating over snap
instead of over snap.docChanges
:将所有文档添加到状态更为典型,您可以通过迭代
snap
而不是通过snap.docChanges
来做到这snap.docChanges
:
let docs = []
snap.forEach(doc =>{
docs.push(doc.data())
})
this.setState({usersArr: docs})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.