【发布时间】:2018-07-26 22:59:05
【问题描述】:
问题
您好,非常感谢愿意帮助我的人,我在 js 中对对象数组进行排序时遇到问题。
在这个组件中,我在 id、hours、day 和 active 中保留了一个数组 this.state。
我的问题是,当我尝试对 object.hours 数组进行排序时,该函数不会按照我的逻辑和对该比较器的理解进行排序,即使排序表达式为 false,该数组也保持不变。
可以在sortHoursByTime 声明下找到。
预期行为
if (obj1.toTime < obj2.fromTime) 然后对obj1 排在首位的数组进行排序。
代码:
export default class SetWorkingHours extends Component {
constructor() {
super();
this.state = {
workingDays: ['א׳', 'ב׳', 'ג׳', 'ד׳', 'ה׳', 'ו׳'].map((day, _id) => ({
_id,
name: day,
hours: [],
active: false,
})),
activeButton: -1,
}
}
static defaultProps = {};
sortHoursByTime(day) {
let sortedDays = day;
sortedDays.hours.sort((obj1,obj2) => obj1.fromTime < obj2.toTime);
this.setState({workingDays: sortedDays});
}
appendWorkingHours = (hours) => {
let dateHours = {
fromTime: this.formatDateToHourString(new Date(hours.fromDate)),
toTime: this.formatDateToHourString(new Date(hours.toDate))
};
let selectedWorkingDays = this.state.workingDays;
selectedWorkingDays.forEach((day) => {
if (day.active && this.isHoursValid(day, dateHours)) {
day.hours.push(dateHours);
this.sortHoursByTime(day)
}
});
this.setState({workingDays: selectedWorkingDays})
} // Editor's note: the closing curly brace of appendWorkingHours method
// was missing, so I added this line.
};
环境
react-native -v: "0.54.2"
节点-v:v9.8.0
npm -v: 5.6.0
yarn --version: 1.5.1
目标平台:iOS
操作系统:OSX
【问题讨论】:
-
.sort比较器函数应该返回一个数字,但你的返回一个布尔值。尝试将其更改为(obj1,obj2) => obj1.fromTime - obj2.toTime。
标签: javascript arrays react-native