简体   繁体   中英

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.

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:

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).

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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