根据特定的默认列对 table 进行排序

Sort table based on a specific default column

我是 ReactJS 的新手。我有一个 table,通过单击每一列 header 进行排序。这是我的代码:

import React, { useState, useEffect } from 'react'
import { getUsers } from '../../services/userService'

const Table = () => {

const [users, setUsers] = useState([]);
const [currentUsers, setCurrentUsers] = useState([]);
const [search, setSearch] = useState('');
const [isSorted, setIsSorted] = useState(false);
const [valueHeader, setValueHeader] = useState({title: "",body: ""}); //Value header state
const [sortedUsers, setSortedUsers] = useState([]);


const pageItemCount = 15
const [pageCount, setPageCount] = useState(0)
const [currentPage, setCurrentPage] = useState(1)

useEffect(async () => {
    try {
        const response = await getUsers(search);
        setUsers(response.data.users);
        setPageCount(Math.ceil(response.data.users.length / pageItemCount))
        setCurrentUsers(response.data.users.slice(0, pageItemCount))
    } catch (error) { }
}, [search]);

const sortFn = (userA, userB) => {
  // sort logic here, it can be whatever is needed
  // sorting alphabetically by `first_name` in this case
  return userA[valueHeader.body].localeCompare(userB[valueHeader.body]) //<== Use value of culumn header
}

useEffect(() => {
    if (isSorted) {
      setSortedUsers(currentUsers.slice().sort(sortFn))
    } else {
      setSortedUsers(currentUsers)
    }
  }, [isSorted, currentUsers, valueHeader]) //<== add valueHeader to dependency

const toggleSort = (target) => {
  setIsSorted(!isSorted)
  setValueHeader({
    title: target,
    body: target == "name" ? "first_name" : "mobile_number"
  }) //<=== set state of value header
}

const changePage = (i) => {
    setCurrentPage(i)
    const startItem = ((i - 1) * pageItemCount) + 1
    setCurrentUsers(users.slice(startItem - 1, (pageItemCount * i)))
}

const handleChange = (event, value) => {
    changePage(value);
}

    return (
        <div dir='rtl' className='bg-background mt-10 px-5 rd1200:px-30 overflow-auto'>
           
            <table className='w-full border-separate rounded-md'>
                <thead>
                    <tr className='bg-text-secondary text-white shadow-sm text-center'>
                        <th className='p-2' onClick={()=>toggleSort("name")}>name</th>
                        <th className='p-2' onClick={()=>toggleSort("mobile")}>mobile</th>
                    </tr>
                </thead>
                <tbody>
                    {sortedUsers.map((item, index) =>
                        <tr key={item.id} className={index % 2 === 0 ? 'bg-white shadow-sm text-center' : 'bg-text bg-opacity-5 shadow-sm text-center'}>
                            <td className='text-text text-sm p-2'>{item.first_name}</td>
                            <td className='text-text text-sm p-2'>{item.mobile_number}</td> 
                        </tr>
                    )}
                </tbody>
            </table>
            <Pagination className="mt-2 pb-20" dir='ltr' page={currentPage} count={pageCount} onChange={handleChange} variant="outlined" shape="rounded" />                
        </div>
    )
}

export default Table

现在,当我单击每一列 header 时,我的 table 会根据该列进行排序。我想知道是否可以首先根据特定列对 table 进行排序。我的意思是,例如,起初我的 table 默认基于 name 列进行排序(无需单击列 header 或执行任何其他操作)。

你可以在useEffect中做到:

useEffect(() => {
toggleSort("name");
}, [])
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>