【问题标题】:How can I implement sorting in my crud table? [closed]如何在我的 crud 表中实现排序? [关闭]
【发布时间】:2021-08-23 14:46:07
【问题描述】:

这是我的后端代码

app.get("/sortedcustomers", (req, res) => {
  db.query("SELECT * FROM customer_info ORDER BY contacted", (err, result) => {
    if (err) {
      console.log(err);
    } else {
      res.send(result);
    }
  });
});

这给了我这种形式的数据: [{"ID":1,"name":"Queen","email":"Queen@gmail.com","counts_of_visit":13,"latest_time_of_visit":"2021-03-12T12:08:23.000Z" ,"已联系":"No"},{"ID":3,"name":"Alex","email":"Alex@gmail.com","counts_of_visit":7,"latest_time_of_visit":"2021- 04-30T09:50:23.000Z","contacted":"No"},{"ID":2,"name":"Wayne","email":"Wayne@gmail.com","counts_of_visit": 10,"latest_time_of_visit":"2021-04-30T09:50:23.000Z","contacted":"Yes"},{"ID":4,"name":"Jack","email":"Jack@ gmail.com","counts_of_visit":3,"latest_time_of_visit":"2021-04-30T09:50:23.000Z","contacted":"Yes"}]

然后是我的前端代码:

function Home(props) {
  const [customerList, setCustomerList] = useState([]); //store all that information of the database in a list
  //make an axios request to get information from database
  useEffect(() => {
    Axios.get("http://localhost:3001/customers").then((response) => {
      setCustomerList(response.data);
    });
  }, []);

  const getSortedCustomerList = () => {
    Axios.get("http://localhost:3001/sortedcustomers").then((response) => {
      setCustomerList(response.data);
    });
  };
  const updateCustomerContacted = (ID) => {
    Axios.put("http://localhost:3001/update", {
      contacted: newContacted,
      ID: ID,
    }).then((response) => {
      setCustomerList(
        customerList.map((val) => {
          return val.ID == ID
            ? {
                ID: val.ID,
                name: val.name,
                email: val.email,
                counts_of_visit: val.counts_of_visit,
                latest_time_of_visit: formatDatetime(val.latest_time_of_visit),
                contacted: newContacted,
              }
            : val;
        })
      );
    });
  };

  //function to format the datetime to correct format
  const formatDatetime = (datetime) => {
    const dateStr = new Date(datetime).toLocaleDateString("en-CA");
    const timeStr = new Date(datetime).toLocaleTimeString();
    return `${dateStr} ${timeStr}`;
  };

  const deleteCustomer = (ID) => {
    Axios.delete(`http://localhost:3001/stats/delete/${ID}`).then(
      (response) => {
        setCustomerList(
          customerList.filter((val) => {
            return val.ID != ID;
          })
        );
      }
    );
  };

  //pagination
  const [pageNumber, setPageNumber] = useState(0);
  const customersPerPage = 5; //change this number according to desired number of rows in a page
  const pagesVisited = pageNumber * customersPerPage;
  const displayCustomers = customerList
    .slice(pagesVisited, pagesVisited + customersPerPage)
    .map((val, key) => {
      const dateStr = new Date(val.latest_time_of_visit).toLocaleDateString(
        "en-CA"
      );
      const timeStr = new Date(val.latest_time_of_visit).toLocaleTimeString();
      const dateTime = `${dateStr} ${timeStr}`;
      const my_serial = key + pageNumber * customersPerPage;
      return (
        <tr>
          {/*}
          <td>{val.ID}</td>
      */}
          <td>{my_serial + 1}</td>
          <td>{val.name}</td>
          <td>{val.email}</td>
          <td>{val.counts_of_visit}</td>
          <td>{dateTime}</td>
          <td>{val.contacted}</td>
          <td>
            <select
              onChange={(event) => {
                setNewContacted(event.target.value);
              }}
            >
              <option value="" selected disabled hidden>
                Select Yes/No
              </option>
              <option value="Yes">Yes</option>
              <option value="No">No</option>
            </select>
            <button
              className="btn btn-primary"
              onClick={() => {
                updateCustomerContacted(val.ID);
              }}
            >
              Update
            </button>
          </td>
          <td>
            <button
              className="btn btn-danger"
              onClick={() => {
                deleteCustomer(val.ID);
              }}
            >
              Delete
            </button>
          </td>
        </tr>
      );
    });
  //to account for the fact that total number of customers cannot be divided equally among the pages
  const pageCount = Math.ceil(customerList.length / customersPerPage);
  //page change
  const changePage = ({ selected }) => {
    setPageNumber(selected);
  };

  //update contacted column
  const [newContacted, setNewContacted] = useState(0);

  //export to csv function

  const DataSet = [
    {
      columns: [
        {
          title: "S/N",
          style: { font: { sz: "18", bold: true } },
          width: { wpx: 125 },
        }, // width in pixels
        {
          title: "Customer Information",
          style: { font: { sz: "18", bold: true } },
          width: { wpx: 250 },
        }, // width in pixels
        {
          title: "Customer Email",
          style: { font: { sz: "18", bold: true } },
          width: { wpx: 250 },
        }, // width in pixels
        {
          title: "Counts of Visit",
          style: { font: { sz: "18", bold: true } },
          width: { wpx: 175 },
        }, // width in pixels
        {
          title: "Latest Time of Visit",
          style: { font: { sz: "18", bold: true } },
          width: { wpx: 250 },
        }, // width in pixels
        {
          title: "Contacted?",
          style: { font: { sz: "18", bold: true } },
          width: { wpx: 250 },
        }, // width in pixels
      ],
      data: customerList.map((val, key) => [
        { value: key + 1, style: { font: { sz: "14" } } },
        { value: val.name, style: { font: { sz: "14" } } },
        { value: val.email, style: { font: { sz: "14" } } },
        { value: val.counts_of_visit, style: { font: { sz: "14" } } },
        {
          value: formatDatetime(val.latest_time_of_visit),
          style: { font: { sz: "14" } },
        },
        { value: val.contacted, style: { font: { sz: "14" } } },
      ]),
    },
  ];

  return (
    <div>
        <GridItem xs={12} sm={12} md={12}>
          <Card>
            <CardHeader color="warning">
              <h4 className={classes.cardTitleWhite}>Customer Information</h4>
              <p className={classes.cardCategoryWhite}></p>
            </CardHeader>
            <CardBody>
              <div className="dashboardcontainer">
                <div className="container"></div>
                <table className="customertable">
                  <thead>
                    <tr>
                      {/*}
                      <th>S/N</th>
              */}
                      <th>S/N</th>
                      <th>Customer Name</th>
                      <th>Customer Email</th>
                      <th>Counts of Visit</th>
                      <th>Latest Time of Visit</th>
                      <th onClick={getSortedCustomerList}>Contacted?</th>
                      <th>Edit Contacted</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>{displayCustomers}</tbody>
                </table>
                <ReactPaginate
                  previousLabel={"Previous"}
                  nextLabel={"Next"}
                  pageCount={pageCount}
                  onPageChange={changePage}
                  containerClassName={"paginationBttns"}
                  pageLinkClassName={"paginationNumber"}
                  previousLinkClassName={"previousBttn"}
                  nextLinkClassName={"nextBttn"}
                  disabledClassName={"paginationDisabled"}
                  activeClassName={"paginationActive"}
                />
                <ExcelFile
                  filename="Customer Information"
                  element={
                    <button
                      type="button"
                      className="btn btn-success float-right m-3"
                    >
                      Export to Excel
                    </button>
                  }
                >
                  <ExcelSheet
                    dataSet={DataSet}
                    name="Customer Information Report"
                  ></ExcelSheet>
                </ExcelFile>
              </div>
            </CardBody>
          </Card>
        </GridItem>
      </GridContainer>
    </div>
  );
}

但是关于我的前端的事情是,当我点击“已联系?”时标题列确实显示了排序的数据,但是如何让它显示反向排序的列表,然后在最后一次单击时显示正常的未排序客户列表。所以第一次点击排序列表有效,但第二次点击排序反向列表不起作用,第三次点击未排序列表不起作用。

所以,基本上,我有这个 crud 表,当我点击联系列时,它会相应地对自己进行排序,但是当我再次点击时它不会以相反的顺序排序,然后当我再次点击时它不会回到未排序的顺序,如何解决?

【问题讨论】:

    标签: javascript node.js reactjs frontend backend


    【解决方案1】:

    试试

    customerList.sort(function(a, b) {
      return b - a;
    })
    

    ,或者,如果这不起作用:

    customerList.reverse()
    

    【讨论】:

    • 两者都不起作用
    • 我添加了``` const displaySortedCustomers = () => { customerList.sort(function (a, b) { return b - a; }); }; ```然后在列标题上添加了一个onClick方法来运行这个函数但是它没有排序。
    猜你喜欢
    • 2014-12-04
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2018-08-01
    相关资源
    最近更新 更多