代码之家  ›  专栏  ›  技术社区  ›  Gigi101

列表不会按日期排序

  •  0
  • Gigi101  · 技术社区  · 2 年前

    我正在尝试按时间顺序显示订单列表,但我无法实现这一点。我的数据存储在Mongodb数据库中,我正在使用react。我的前端是js。我尝试过使用排序:

    {orders.sort((a,b) => b.createdAt - a.createdAt).map((order) => (....)}

    但一切都没有改变。我真的很感激任何关于如何解决这个问题的帮助或建议。非常感谢。

    此页面的完整代码:

    import React, { useEffect } from 'react';
    import { useDispatch, useSelector } from 'react-redux';
    import { deleteOrder, listOrders } from '../actions/orderActions';
    import LoadingBox from '../components/LoadingBox';
    import MessageBox from '../components/MessageBox';
    import { ORDER_DELETE_RESET } from '../constants/orderConstants';
    
    export default function OrderListScreen(props) {
      const orderList = useSelector((state) => state.orderList);
      const { loading, error, orders } = orderList;
      const orderDelete = useSelector((state) => state.orderDelete);
      const {
        loading: loadingDelete,
        error: errorDelete,
        success: successDelete,
      } = orderDelete;
    
      const userSignin = useSelector((state) => state.userSignin);
      const { userInfo } = userSignin;
      const dispatch = useDispatch();
      useEffect(() => {
        dispatch({ type: ORDER_DELETE_RESET });
        dispatch(listOrders({ seller: sellerMode ? userInfo._id : '' }));
      }, [dispatch, sellerMode, successDelete, userInfo._id]);
      const deleteHandler = (order) => {
        // TODO: delete handler
        if (window.confirm('Are you sure to delete?')) {
            dispatch(deleteOrder(order._id));
          }
      };
    
    
      return (
        <div>
          <h1>Orders</h1>
          {loadingDelete && <LoadingBox></LoadingBox>}
          {errorDelete && <MessageBox variant="danger">{errorDelete}</MessageBox>}
          {loading ? (
            <LoadingBox></LoadingBox>
          ) : error ? (
            <MessageBox variant="danger">{error}</MessageBox>
          ) : (
            <table className="table">
              <thead>
                <tr className="table_row">
                  <th className="main">ID</th>
                  <th className="main">DATE</th>
                  <th className="main">TOTAL</th>
                  <th className="main">ACTIONS</th>
                </tr>
              </thead>
              <tbody>
                {orders.sort((a,b) => b.createdAt - a.createdAt).map((order) => (
                  <tr className="table_row" key={order._id}>
                    <td className="data">{order._id}</td>
                    <td className="data">{order.createdAt.substring(0, 10)}</td>
                    <td className="data">{order.totalPrice.toFixed(2)}</td>
                    <td className="data">
                      <button
                        type="button"
                        className="small"
                        onClick={() => {
                          props.history.push(`/order/${order._id}`);
                        }}
                      >
                        Details
                      </button>
                      <button
                        type="button"
                        className="small"
                        onClick={() => deleteHandler(order)}
                      >
                        Delete
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      );
    }
    
    
    1 回复  |  直到 2 年前
        1
  •  2
  •   Mushroomator    2 年前

    如果是ISO-8601字符串,可以使用 Date 构造函数,该构造函数将字符串解析为一个日期,然后可以进行减法运算。

    // ISO string creates a ISO-8601 string
    const dates = [new Date(2022, 4, 26).toISOString(), new Date(2022, 4, 23).toISOString(), new Date(2022, 3, 23).toISOString(), new Date(2022, 5, 23).toISOString(), new Date(2021, 4, 23).toISOString()];
    console.log(dates);
    
    
    dates.sort((a, b) => new Date(a) - new Date(b));
    console.log(dates);

    如果你真的想要 日期 要使用的对象可以使用 map() 之前将返回一个 日期 可以使用的对象。

    // ISO string creates a ISO-8601 string
    const dates = [new Date(2022, 4, 26).toISOString(), new Date(2022, 4, 23).toISOString(), new Date(2022, 3, 23).toISOString(), new Date(2022, 5, 23).toISOString(), new Date(2021, 4, 23).toISOString()];
    console.log(dates);
    const sortedParsedDates = dates.map(dateStr => new Date(dateStr)).sort((a, b) => a - b);
    console.log(sortedParsedDates);
    // now we actually have Date objects we can work with
    console.log(sortedParsedDates[0] instanceof Date);