简体   繁体   English

为什么我不能为 Firebase 的文档数据设置状态?

[英]Why I can't set state to Firebase's doc data?

I fetch data from my firestore database like thus:我从我的 firestore 数据库中获取数据,如下所示:

const [songs, setSongs] = useState();

async function getSongs() {
  const songs = collection(db, 'songs');
  const songSnapshot = await getDocs(songs);
  const songList = songSnapshot.docs.map(doc => doc.data());
  setSongs(songList);
  console.log(songList);
  console.log(songs);
};

If I run this, there are two objects in the console, the first one is songList , and the second one is songs :如果我跑这一点,有在控制台的两个对象,第一个是的SongList,而第二个是歌曲

控制台图像在这里

Why is there a difference between the two?为什么两者之间存在差异? What do I do to turn songs back into an array?我该怎么做才能将歌曲变回数组?

"songs" is a CollectionReference and does not contain the data. "songs"是一个CollectionReference ,不包含数据。 "songList" is an array which contains data from the documents returned by getDocs() . "songList"是一个数组,其中包含来自getDocs()返回的文档的数据。 You should set songList in your state instead of songs您应该在您的状态中设置songList而不是songs

From the documentation ,文档中

A CollectionReference object can be used for adding documents, getting document references, and querying for documents (using query()). CollectionReference 对象可用于添加文档、获取文档引用和查询文档(使用 query())。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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