【发布时间】: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函数中的a和b是什么,它们是数字吗?不然b - a怎么会返回数值呢? -
乍一看,有两件事。 1) 你不是在告诉它如何 排序——你是在告诉它每次都进行相同的排序。因此,您需要保存排序状态(即“asc”、“desc”),然后以此为基础进行排序。 2) 您正在尝试设置状态 within 排序比较功能。您应该在所有内容都排序后执行此操作。
-
在你的函数中尝试
setCustomerList([].concat(customerList).sort((a, b) => b.contacted - a.contacted))。 -
@AjeetShah codesandbox.io/s/crud-table-sorting-qroke
标签: javascript reactjs