【问题标题】:React-Hooks: How to sort data in ascending & descending order and show in reusable data table componentReact-Hooks:如何按升序和降序对数据进行排序并显示在可重用的数据表组件中
【发布时间】:2021-04-01 01:27:19
【问题描述】:

在我的应用程序中,我想创建一个可重用的数据表组件。数据来自后端,我需要对这些数据进行排序。数据是数字和字符串。现在我想以升序和降序按钮显示数据。这是我的数据表代码:

//Table Component
const Table = ({ headers, data }) => {
return (
 <table>
 <thead>
   <tr>
     {headers.map(head => (
       <th>{head}</th>
     ))}
    </tr>
  </thead>
 <tbody>
  {data.map(row => (
    <tr>
      {headers.map(head => (
        <td>{row[head]}</td>
      ))}
    </tr>
   ))}
 </tbody>
</table>


//app.js

 export default function App() {
 const headers = ['userId', 'id', 'title', 'body'];
 
  useEffect(() => {
    const getPosts = async () => {
        const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
        setData(data);
    };
    
    getPosts();
}, []);

 const filteredData = slice.filter(
    post => post.title.toLowerCase().includes(keyword) || post.body.toLowerCase().includes(keyword),
);

const onInputChange = e => {
    e.preventDefault();
    setKeyword(e.target.value.toLowerCase());
};
 

  return (
   <div>
     div className="table-search-form">
              <input
                  className="form-control"
                  type="text"
                  placeholder="Search..."
                  onChange={onInputChange}
                  />
                  </div>
    <DataTable headers={headers} posts={filteredData} />
   </div>
  );
  }

【问题讨论】:

    标签: reactjs api sorting react-hooks


    【解决方案1】:

    我使用数据表包找到了这个解决方案。这里https://www.npmjs.com/package/react-data-table-component-extensions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      相关资源
      最近更新 更多