【问题标题】:React.js Table Sorting with Dynamic Data使用动态数据进行 React.js 表排序
【发布时间】:2022-01-31 16:40:41
【问题描述】:

一些动态数据有两个不同的 API 服务端点,如下所示。

// from API Service A, All value are realtime changing
{
 stack : 10
 over : 2
 flow : 4
}
// from API Service B, All value are realtime changing
{
 stack : 4
 over : 1
 flow : 2
}

两个不同API服务的key是一样的,但是实时变化的值不同。

所以我想用表格说明这些差异。

我用 react.js 编写代码来显示这个数据表,如下所示。

import { useState, useEffect } from 'react';
function App(){
 const [commonKey, setCommonKey] = useState([stack, over, flow]);
 const [dataA, setDataA] = useState({});
 const [dataB, setDataB] = useState({});

 useEffect(()=> {
  // ...periodically fetch data from API Service A and setDataA(response)
  // ...periodically fetch data from API Service B and setDataB(response)
 } ,[]);

 return (
 <>
  <table>
   <thead>
    <th>key</th>
    <th>valueA</th>
    <th>valueB</th>
    <th>A-B</th> // sorting function needed by this field value(A minus B).
   </thead>
   <tbody>
    commonKey.map((keyField)=>{
     <Mytr key={keyField} keyField={keyField} dataA={dataA[keyField]} dataB={dataB[keyField]} />
    });
   </tbody>
  </table>
 </>
)}

function Mytr({keyField, dataA, dataB}){
 return (
 <>
  <tr>
   <td>{keyField}</td>
   <td>{dataA}</td>
   <td>{dataB}</td>
   <td>{dataA - dataB}</td> // sorting function needed by this field value.
  </tr>
 </>
)}

export default App;

在这种情况下如何添加按A-B值函数排序

p.s 对不起我的英语不好。

【问题讨论】:

    标签: reactjs sorting html-table react-table


    【解决方案1】:

    你可以在useEffect钩子中sortcommonKeys,如下所示。

      useEffect(() => {
        // ...periodically fetch data from API Service A and setDataA(response)
        // ...periodically fetch data from API Service B and setDataB(response)
    
        // get a copy of the commonKey array
        const newArr = [...commonKey];
        // sort the keys using differece of two consecutive diffs
        newArr.sort((p, q) => dataA[p] - dataB[p] - (dataA[q] - dataB[q]));
        // set the sorted array to state
        setCommonKey(newArr);
      }, []);
    

    为避免滚动问题,请保存scrollY 位置,并在commonKeyuseLayoutEffect 中更新后滚动到该位置。

     useEffect(() => {
        const updatePosition = () => {
          setCurrentScrollY(window.scrollY);
        };
        window.addEventListener("scroll", updatePosition);
        updatePosition();
        return () => window.removeEventListener("scroll", updatePosition);
      }, []);
    
      useLayoutEffect(() => {
        window.scrollTo(0, currentScrollY);
      }, [commonKey]);
    

    【讨论】:

    • @reaver 爱人,如果您还有问题,请告诉我
    • 谢谢,虽然排序效果很好,排序后每次重新渲染时都会滚动到顶部窗口
    • 你能更新沙箱来重现滚动问题吗?
    • codesandbox.io/s/goofy-sea-08w9k 每次排序时自动滚动到顶部。顺便说一句,对不起,脏代码。
    • 是的,由于重新渲染。当 useEffect 更改列表时,触发重新渲染和 useLayoutEffect 在列表的 DOM 突变之后和列表被绘制到 DOM 之前运行并保留滚动位置。
    猜你喜欢
    • 2021-08-02
    • 1970-01-01
    • 2012-06-27
    • 2016-01-29
    • 1970-01-01
    • 2021-01-10
    • 2017-05-18
    • 2019-01-27
    • 2016-09-13
    相关资源
    最近更新 更多