首页 > 解决方案 > 按日期对表行进行排序,比较种子文件中的 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>
    );
  }
}

我想我需要按日期排序,然后映射返回的内容以呈现表格行。它似乎没有任何效果。谢谢!

标签: javascriptrubyreactjssortingdate

解决方案


您的排序函数需要返回 -1、0 或 1 才能正常工作。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


推荐阅读