简体   繁体   English

如何正确排序和渲染 ReactJs 中的表格?

[英]How to sort and render table in ReactJs properly?

Help, people:) I made the same function (sorting function) in pure JS, but after sorting, I rendered the table every time, ie created a new one with sorted data, but I don't understand how to implement it in React.求助各位:)我用纯JS做了同样的function(排序功能),但是排序之后,我每次都渲染表格,即创建一个新的排序数据,但我不明白如何在React中实现它.

How exactly do I recreate the body of the table every time I do something with the data?每次我对数据做某事时,究竟如何重新创建表的主体?

 import tableData from './data';
 import React, { useEffect, useState } from 'react';
 import './App.css';

 function App() {
   let [data, setData] = useState(tableData);
   let clickOnPrice = false;

 const sortByPrice = () => {
   let sorted = data;
   if(!clickOnPrice) {
      sorted.sort((a, b) => parseInt(a.price.replace(/ /g, '')) - parseInt(b.price.replace(/ /g, '')));
      clickOnPrice = true;
   }else {
      sorted.sort((a, b) => parseInt(b.price.replace(/ /g, '')) - parseInt(a.price.replace(/ /g, '')));
      clickOnPrice = false;
   }
 }



return (
<div className='App'>
 <table>
<thead>
  <tr>
    <th>№</th>
    <th>Название</th>
    <th><button className='price_btn' onClick={() => sortByPrice()}>Цена<span className="icons descending_icon">&nbsp;↑</span></button></th>
    <th><button className='price_btn'>Количество</button></th>
    <th>В рассрочку</th>
  </tr>
</thead>
<tbody>
  {data.map((item, index) => (
    <tr key={index}>
      <td>{index + 1}</td>
      <td>{item.name}</td>
      <td>{item.price}</td>
      <td>{item.count}</td>
      <td>{(item.instalment) ? '✅' : ''}</td>
    </tr>
   ))}
   </tbody>
 </table>
 </div>
 );
 }

export default App;

You should use data state variable to store sorted data as:您应该使用data state 变量将排序后的数据存储为:

const sortByPrice = () => {
      setData(data.sort((a, b) => parseInt(a.price.replace(/ /g, '')) - parseInt(b.price.replace(/ /g, ''))));   
 }

You do not need even the variable named clickOnPrice if you want to sort data only in one way (either desc or asc).如果只想以一种方式(desc 或 asc)对数据进行排序,则甚至不需要名为clickOnPrice的变量。

Moreover, replace此外,更换

    <th><button className='price_btn' onClick={() => sortByPrice()}>Цена<span className="icons descending_icon">&nbsp;↑</span></button></th>

with

    <th><button className='price_btn' onClick={sortByPrice}>Цена<span className="icons descending_icon">&nbsp;↑</span></button></th>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM