gpt4 book ai didi

javascript - 在将值设置为 state 之前对 Firebase 快照进行排序

转载 作者:行者123 更新时间:2023-12-01 02:34:51 25 4
gpt4 key购买 nike

我从 Firebase 获取值,因为 Firebase 不支持组合多个 orderByChild(),我想我们必须在客户端对值进行排序

Firebase 查询为

componentDidMount() {
const device_id = DeviceInfo.getUniqueID();
this.codesRef = firebase.database().ref(`codes`).orderByChild('owner').equalTo(device_id);
this.codesRef.keepSynced(true);
this.codesRef.on('value', this.handleCodesUpdate);
}

componentWillUnmount() {
this.codesRef.off('value', this.handleCodesUpdate);
}

handleCodesUpdate(snapshot) {
if (snapshot.val()) {

//sort the snapshot before assigning to state

this.setState({ codes: snapshot.val() });
}
else {
this.setState({ codes: {} });
}
}

Firebase 响应

{ 
"-L1SI6Ceu2mPCxDU89NH":{
"status":0,
"purchase_date":1514467520472,
"title":"Mnic Htod",
"start_in":0,
"owner":"fgdgfdgdfgdfgdfgdfg",
"valid_duration":1,
"createdAt":"2017-11-28 18:55:20",
"code":"218688"
},
"-L1SI3krvOYDaqr8g_cs":{
"status":0,
"purchase_date":1514467510437,
"title":"Banfog",
"start_in":0,
"owner":"xgdfgdfgdfgfdgdf",
"valid_duration":1,
"createdAt":"2017-11-28 18:55:10",
"code":"804452"
},
"-L1SI1eFHX7a0_RFhZtW":{
"status":0,
"purchase_date":1514467501822,
"title":"Blizaard",
"start_in":0,
"owner":"xcvxcvxcvxcvxcv",
"valid_duration":1,
"createdAt":"2017-11-28 18:55:1",
"code":"300149"
}
}

我想按createdAt对数据进行排序

期待急需的帮助

谢谢

最佳答案

最简单的方法是使用如下代码片段:

var sortedKeys = Object.keys(json).sort(function(a,b) { 
return json[b].createdAt < json[a].createdAt
});

查看这个可运行版本:

var json = { 
"-L1SI6Ceu2mPCxDU89NH":{
"status":0,
"purchase_date":1514467520472,
"title":"Mnic Htod",
"start_in":0,
"owner":"fgdgfdgdfgdfgdfgdfg",
"valid_duration":1,
"createdAt":"2017-11-28 18:55:20",
"code":"218688"
},
"-L1SI3krvOYDaqr8g_cs":{
"status":0,
"purchase_date":1514467510437,
"title":"Banfog",
"start_in":0,
"owner":"xgdfgdfgdfgfdgdf",
"valid_duration":1,
"createdAt":"2017-11-28 18:55:10",
"code":"804452"
},
"-L1SI1eFHX7a0_RFhZtW":{
"status":0,
"purchase_date":1514467501822,
"title":"Blizaard",
"start_in":0,
"owner":"xcvxcvxcvxcvxcv",
"valid_duration":1,
"createdAt":"2017-11-28 18:55:1",
"code":"300149"
}
}
var sortedKeys = Object.keys(json).sort(function(a,b) { return json[b].createdAt < json[a].createdAt });
console.log(sortedKeys);

需要注意的几点:

  1. 您无法让 Firebase 在服务器端执行此操作,因为它只能对单个属性进行排序/过滤。请参阅http://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase .
  2. 当您调用 snapshot.val() 时,您将丢弃 Firebase 为数据返回的订单信息。我认为这不是问题,但如果您想保持该顺序,请使用 snapshot.forEach() 循环结果。请参阅orderByChild not working in Firebase .
  3. 您的日期格式在最后一个子项中似乎有缺陷:"createdAt":"2017-11-28 18:55:1"。应该是 "createdAt":"2017-11-28 18:55:01" 以使其可靠地排序。

关于javascript - 在将值设置为 state 之前对 Firebase 快照进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48009319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com