我一直试图按日期对数组(schoolClasses)中的对象进行排序,但没有成功。
我使用Firebase获得所有课程,并且,对于每个课程,我都使用Firebase获取其主题名称。
然后我按日期对数组进行排序并调用setState,传递已排序的数组:
export default class SchoolClassesScreen extends React.Component {
constructor() {
super();
this.state = {
schoolClasses: [],
currentClass: {}
};
}
componentDidMount() {
FirebaseDatabase.database().ref('schoolClasses').once('value').then(snapshot => {
let schoolClasses = snapshot.val();
Object.keys(schoolClasses).forEach(key => {
let schoolClass = schoolClasses[key];
FirebaseDatabase.database().ref('subject/' + schoolClass.subject).once('value').then(snapshot => {
schoolClass.subject = snapshot.val().name;
let schoolClasses = this.state.schoolClasses.slice();
schoolClasses.push(schoolClass);
schoolClasses.sort((sc1, sc2) => new Date(sc1.date) - new Date(sc2.date));
this.setState({schoolClasses: schoolClasses, currentClass: schoolClasses[0]});
});
});
});
}
render() {
// ...
}
}
排序与否并没有任何区别。数组总是以相同的顺序。
我错过了什么?感谢。
更新1
数据库结构:
{
"schoolClasses" : {
"schoolClass1" : {
"date" : "2017-11-07 18:45:00",
"subject" : "security"
},
"schoolClass3" : {
"date" : "2017-11-09 18:45:00",
"subject" : "database1"
},
"schoolClass2" : {
"date" : "2017-11-08 18:45:00",
"subject" : "database1"
}
},
"subject" : {
"security" : {
"name" : "I.T. Security"
},
"database1" : {
"name" : "Database I"
}
}
}