我有一个使用以下代码查询 Firebase 的 React 应用:
const usersRef = firebase.database().ref('users').orderByChild('totalSubs');
usersRef.on('value', (snapshot) => {
let users = snapshot.val();
let newState = [];
for (let user in users) {
newState.push({
id: user,
displayName: users[user].displayName,
totalSubs: users[user].totalSubs,
userImg: users[user].userImg
});
}
this.setState({
users: newState
});
});
可以在此处查看我的“用户”Firebase 结构。
我正在测试 3 个不同的 Google 帐户,这就是为什么每个用户都会显示我的名字。
我希望能够在我的 React 应用程序中显示每个用户,按 totalSubs
的降序排列,例如totalSubs
最高的用户位于顶部。
从其他帖子中,我认为 .orderByChild('totalSubs');
会排序数据并允许这样做,但它不起作用。谁能告诉我我错过了什么?
最佳答案
您的查询是正确的,但您需要调整用于从返回的 DataSnapshot
中提取数据的方法。 .
来自working with lists of data documentation :
Attaching a
value
observer to a list of data will return the entire list of data as a single snapshot which you can then loop over to access individual children.Even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result:
ref.once('value', function(snapshot) { snapshot.forEach(function(childSnapshot) { var childKey = childSnapshot.key; var childData = childSnapshot.val(); // ... }); });
因此,对于示例代码,您需要进行一些更改并使用 forEach
迭代返回的子项:
const usersRef = firebase.database().ref('users').orderByChild('totalSubs');
usersRef.on('value', (snapshot) => {
let newState = [];
snapshot.forEach(function(childSnapshot) {
newState.push({
id: childSnapshot.key,
displayName: childSnapshot.val().displayName,
totalSubs: childSnapshot.val().totalSubs,
userImg: childSnapshot.val().userImg
});
});
this.setState({
users: newState
});
});
关于javascript - ReactJS 和 Firebase - 订购数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47303690/