javascript - 按日期对表行进行排序,比较种子文件中的 DateTime 和 Date.now()
问题描述
我正在尝试呈现一个表格,其中包含我的种子文件中包含 DateTime 的约会时间列表。我正在尝试按日期对它们进行排序,并根据该时间是过去还是将来有条件地渲染。我正在努力正确格式化它以便能够排序。
我已经从状态转换了对象数组,以便每个日期属性都采用 Javascript 日期格式。
以下是相关部分:
import React, { Component } from "react";
export default class LessonsList extends Component {
constructor(props) {
super(props);
this.state = {
current_time: Date.now(),
lessons: []
};
}
componentDidMount() {
const token = localStorage.getItem("current_user");
fetch("http://localhost:3000/api/v1/lessons/", {
method: "GET",
headers: {
Authorization: `Bearer ${token}`
}
})
.then(resp => resp.json())
.then(lessons => {
lessons.map(lesson => {
lesson.timeslot.realdate = new Date(lesson.timeslot.realdate);
return lesson;
});
this.setState({
lessons
});
});
}
sortDates = () => {
let sortedDates = this.state.lessons.sort(function(date, lesson) {
return Date.now(date) - lesson.timeslot.realdate;
});
return sortedDates;
};
renderTableData = () => {
// map over sorted array from separate function
return this.state.lessons.length ? (
this.sortDates().map(lesson => {
console.log(lesson.timeslot.realdate > Date.now());
return (
<tr>
<th scope="row">{lesson.id}</th>
<td>{lesson.teacher.name}</td>
<td>
{lesson.timeslot.month_name} {lesson.timeslot.date}
</td>
<td>{lesson.timeslot.hour}:00</td>
</tr>
);
})
) : (
<h6>'Loading'</h6>
);
};
render() {
console.log(this.state.lessons);
return (
<div>
<h1 className="lesson-h1">Lessons</h1>
<br></br>
<div className="col-md-12 student-button-group"></div>
<table className="table table-striped lesson-table">
<thead>
<tr>
<th scope="col">Lesson ID</th>
<th scope="col">Teacher</th>
<th scope="col">Date</th>
<th scope="col">Time</th>
</tr>
</thead>
<tbody>{this.renderTableData()}</tbody>
</table>
</div>
);
}
}
我想我需要按日期排序,然后映射返回的内容以呈现表格行。它似乎没有任何效果。谢谢!
解决方案
您的排序函数需要返回 -1、0 或 1 才能正常工作。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
推荐阅读
- bash - 如何将变量和管道命令转换为另一个变量
- java - spring boot中如何仅使用一个源代码划分测试服务器和服务服务器
- javascript - 图片删除/删除代码语法使用cshtml(base64图像)
- android - 如何从第三方应用程序(如 Camscanner 或 officelens)访问文件并获取它们
- java - Junit 测试中的 SpringBoot 容器
- c++ - 如何找到 char 指针指向的地址?
- azure - 为什么网络隔离允许在 Azure 中进行更多横向扩展?
- node.js - React.JS - 在 `onClick` 事件上调用函数会导致 `this` 在函数中未定义
- javascript - bind和箭头函数的内存消耗与理论不一致
- java - 如何在参数中正确使用泛型