【问题标题】:How to fix my sorting function in my crud table?如何在我的 crud 表中修复我的排序功能?
【发布时间】:2021-06-06 12:01:49
【问题描述】:

前端代码

  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 displaySortedCustomers = () => {
    customerList.sort(function (a, b) {
      setCustomerList(customerList);
      return b - a;
    });
  };
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>
      );
    });

<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={displaySortedCustomers}>Contacted?</th>
                      <th>Edit Contacted</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>{displayCustomers}</tbody>
                </table>

所以我通过引用我的前端代码有一个表格,我在表格列“已联系”中添加了一个 onClick 方法来运行函数 displaySortedCustomers 但它不排序?如何更改代码? 我需要表格在第一次单击时排序,然后在第二次单击时按相反顺序排序,在第三次单击时排序回未排序的顺序。

【问题讨论】:

  • 你为什么把setCustomerList(customerList);放在customerList.sort(function (a, b) { setCustomerList(customerList); return b - a; });里面
  • 此外,您的customerList.sort 函数中的ab 是什么,它们是数字吗?不然b - a怎么会返回数值呢?
  • 乍一看,有两件事。 1) 你不是在告诉它如何 排序——你是在告诉它每次都进行相同的排序。因此,您需要保存排序状态(即“asc”、“desc”),然后以此为基础进行排序。 2) 您正在尝试设置状态 within 排序比较功能。您应该在所有内容都排序后执行此操作。
  • 在你的函数中尝试setCustomerList([].concat(customerList).sort((a, b) =&gt; b.contacted - a.contacted))

标签: javascript reactjs


【解决方案1】:

这是一个简单的例子。

  1. 使用状态来保存排序顺序。

  2. 确保sort compare function 正确(a

  3. 更新数据状态后更改订单状态。

请注意,一旦排序,您只能在另一个方向排序 - 您不能返回问题中提到的“未排序顺序”,除非您将该数据的副本保存在某处并将状态中的数据替换为那个数据。但这似乎没有必要。

const { useState, useEffect } = React;

// Do an inital sort of the array
// We're no longer passing in the data to the component
const customers = ['Bob', 'Andy', 'Joe', 'Sam'].sort();

// Mocked API call that returns the data after 2 seconds
function fakeApiCall() {
  return new Promise((res, rej) => {
    setTimeout(() => res(customers), 2000);
  });
}

function Example() {

  const [ data, setData ] = useState([]);
  
  // Set the state for the order, initially to 'asc'
  const [sortOrder, setSortOrder] = useState('asc');

  useEffect(() => {

    // Call the API (Axios) for the data, then set the state
    fakeApiCall().then(data => setData(data));
  }, []);

  // A function that takes an order type
  // and returns a new function to use with `sort`
  // Note we're using less than and greater than
  // rather than "minus" to determine the sort order
  function comparator(order) {
    return function (a, b) {
      return order === 'asc' ? b.localeCompare(a) : a.localeCompare(b);
    }
   }

  // Sets the state of the sorted data, and then set the order state
  function handleSort() {
    setData(data.sort(comparator(sortOrder)));
    setSortOrder(curr => curr === 'asc' ? 'desc' : 'asc');
  }

  // Add rows to the table using the data
  function getRows() {
    return data.map(name => <tr><td>{name}</td></tr>);
  }

  function getArrow() {
    if (sortOrder === 'asc') return '↑';
    return '↓';
  }

  // Make sure you check to see if the data has loaded
  if (!data.length) return <div>Loading...</div>;

  return (
    <table>
      <thead>
        <th onClick={handleSort}>Customers {getArrow()}</th>
      </thead>
      <tbody>
        {getRows()}
      </tbody>
    </table>
  );
};


ReactDOM.render(
  <Example />,
  document.getElementById("react")
);
table { border-collapse: collapse }
th:hover { cursor: pointer; background-color: #dfdfdf; }
tr { border: 1px solid black; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

【讨论】:

  • For const [ data, setData ] = useState(customers);我可以使用 [] 代替客户吗?另外,我在 customerList 中有一份未排序数据的副本,如何在第 3 次点击时呈现它?
  • @max,当然,这只是排序如何处理状态的一个非常简单示例。如何初始化数据取决于您。
  • 我的原始数据有一个状态 ``` const [customerList, setCustomerList] = useState([]); //将数据库的所有信息存储在列表中 //发出axios请求以从数据库中获取信息 useEffect(() => { Axios.get("localhost:3001/customers").then((response) => { setCustomerList(response.data); }) ; }, []); ```我可以用customerList替换客户吗?如何在第三次点击时呈现customerList?
  • 查看我的编辑@max。我在useEffect 中添加了一个虚假的 API 调用以及一些检查数据是否已加载的代码。
  • {getRows()} 我无法添加它,因为我在 body 中有另一个函数 displayCustomers,这会加载原始当前未排序的数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多