按时间戳顺序过滤firebase数据



我试图通过时间戳(createdAt)从firebase订购轨道ID,但它似乎没有订购,但功能仍然有效。不知道我在哪里出错了?

任何帮助都将是非常感激的。

const [trackList, setTrackList] = useState();
//Option 1
useEffect(() => {
const userID = localStorage.getItem('id')
firebase.database().ref(userID)
.orderByChild('createdAt')
.once('value', (snapshot) => {
const firebaseTracks = snapshot.val();
const trackList = [];
for (let id in firebaseTracks) {
trackList.push({ id, ...firebaseTracks[id] });
}
setTrackList(trackList);
});
}, []);

//Option 2
useEffect(() => {
const userID = localStorage.getItem('id')
const trackRef = firebase.database().ref(userID).orderByChild("createdAt").limitToLast(100);
trackRef.on('value', (snapshot) => {
snapshot.forEach(symptomSnapshot => {
const trackList = [];
const firebaseTracks = symptomSnapshot.val();
for (let id in firebaseTracks) {
trackList.push({ id, ...firebaseTracks[id] });
}
console.log(firebaseTracks)
});
setTrackList(trackList);
});
}, []);

问题是当您在这里调用snapshot.val()时:

firebase.database().ref(userID)
.orderByChild('createdAt')
.once('value', (snapshot) => {
const firebaseTracks = snapshot.val();

获取快照的值返回一个JSON对象,而JSON对象中的键根据定义是无序的。

要按顺序处理结果,使用snapshot.forEach,然后在每个子节点上调用val():

firebase.database().ref(userID)
.orderByChild('createdAt')
.once('value', (snapshot) => {
const trackList = [];
snapshot.forEach((child) => {
trackList.push({ id: child.key, ...child.val() });
}
setTrackList(trackList);
});

最新更新