Reactjs 如何从firebase firestore快照(React挂钩)中获取对象?

Reactjs 如何从firebase firestore快照(React挂钩)中获取对象?,reactjs,firebase,google-cloud-firestore,react-hooks,Reactjs,Firebase,Google Cloud Firestore,React Hooks,我在ReactJS中使用Firebase Firestore,想要获取数据,如何将接收到的全部数据设置为post const [state, setState] = useState([]) useEffect(() => { database .firestore() .collection("news") .get() .then(snapshots => {

我在ReactJS中使用Firebase Firestore,想要获取数据,如何将接收到的全部数据设置为post

const [state, setState] = useState([])    
useEffect(() => {
    database
        .firestore()
        .collection("news")
        .get()
        .then(snapshots => {
            setState(snapshots.docs)
        })
        .catch(err => {
            console.log(err)
        })
})



return(
    <div>
        <div className="px-2">
            <div className="flex -mx-2">
                {state.map(data => <span>{data.title}<span>)}
            </div>
        </div>
    </div>
)
const[state,setState]=useState([])
useffect(()=>{
数据库
.firestore()
.收藏(“新闻”)
.get()
。然后(快照=>{
设置状态(snapshots.docs)
})
.catch(错误=>{
console.log(错误)
})
})
返回(
{state.map(数据=>{data.title}}
)

在.collection上,如果希望使用快照对其进行监视,则可以执行以下操作

      .onSnapshot(function (querySnapshot) {
        const news = [];
        querySnapshot.forEach(function (doc) {
          news.push(doc.data());
        });
        setState(news);
一次通话可以用


在.collection上,如果希望使用快照对其进行监视,则可以执行类似的操作

      .onSnapshot(function (querySnapshot) {
        const news = [];
        querySnapshot.forEach(function (doc) {
          news.push(doc.data());
        });
        setState(news);
一次通话可以用


不要忘记将第二个参数添加到useEffect方法,否则,它将被调用无限次

useEffect(() => {
  ....
}, [])

不要忘记将第二个参数添加到useEffect方法,否则,它将被调用无限次

useEffect(() => {
  ....
}, [])