Я пытаюсь отобразить таблицу со списком встреч, в которой в моем начальном файле есть 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>
);
}
}
Я думаю, мне нужно отсортировать по дате, а затем отобразить то, что возвращается, чтобы отобразить строки таблицы. Это, похоже, не имеет никакого эффекта. Спасибо!