我从fire-base获取值,因为fire-base不支持组合多个orderByChild()
,我想我们必须在客户端对值进行排序
fire-base查询
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
期待急需的帮助
谢谢
答案 0 :(得分:2)
最简单的方法是使用这样的代码段:
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);
&#13;
有几点需要注意:
snapshot.val()
时,您将丢弃Firebase为数据退回的订单信息。我不认为这是一个问题,但是如果你想保持这种排序,请使用snapshot.forEach()
来循环结果。见orderByChild not working in Firebase。"createdAt":"2017-11-28 18:55:1"
。这应该是"createdAt":"2017-11-28 18:55:01"
,以使其可靠地排序。