【发布时间】:2021-01-28 21:05:54
【问题描述】:
我目前正在为 React 应用程序使用“tabulator-tables”版本 4.9.3。
此项目的要求之一是从 websocket 接收实时流数据,其中包含要更新的现有行和要添加的新行的混合。
为了做到这一点,每当我从 websocket 收到一条新数据时,我都会在 componentDidUpdate() 中检查 this.props.data 是否已更改,然后使用 tabulator 提供的 updateOrAddData() 函数进行更新相应的表格。
componentDidUpdate(prevProps) {
const { data } = this.props;
if (data !== prevProps.data) {
this.table.updateOrAddData([data]);
}
}
由于表中填充了来自 websocket 的数据,我注意到 Tabulator 的嵌入式排序算法不会被调用来确定通过 updateOrAddData() 添加到表中的新数据的正确排序位置。如果用户没有显式点击列标题重新排序该数据,则数据将根据用户提供的条件乱序。
我尝试过的:
我尝试的一种可能的解决方案是利用 updateOrAddData() 返回的承诺并手动调用 setSort()。
const { data } = this.props;
this.table.updateOrAddData(data).then(() => {
const sorters = this.table.getSorters();
this.table.setSort(sorters);
});
不幸的是,每当调用 setSort() 时,滚动条都会返回到表格的顶部,因此很难滚动整个表格,因为大约每秒都会收到新数据。
为了演示这个问题,我用一个每秒随机生成数据的 setInterval() 函数替换了 websocket 连接。
我目前使用的代码可以在https://codesandbox.io/s/currying-brook-ck8r3或以下访问。
代码:
import React, { Component, createRef, useEffect, useState } from "react";
import Tabulator from "tabulator-tables";
import "../node_modules/tabulator-tables/dist/css/tabulator.min.css";
class TabulatorTable extends Component {
constructor(props) {
super(props);
this.el = createRef();
this.table = null;
}
componentDidMount() {
const { columns, options } = this.props;
this.table = new Tabulator(this.el, {
columns,
data: [],
...options
});
}
componentDidUpdate(prevProps) {
const { data } = this.props;
if (data !== prevProps.data) {
this.table.updateOrAddData([data]);
}
}
render() {
return <div ref={(el) => (this.el = el)} />;
}
}
const App = () => {
const [mockWsData, setMockWsData] = useState({});
const columns = [
{
field: "id",
title: "ID",
sorter: "number"
},
{
field: "letters",
title: "Random letters",
sorter: "string"
}
];
const options = {
height: "500px",
index: "id",
layout: "fitColumns",
reactiveData: true
};
useEffect(() => {
const generateFakeData = setInterval(() => {
setMockWsData({
id: Math.floor(Math.random() * Math.floor(15)),
letters: Math.random().toString(36).substring(2, 7)
});
}, 500);
return () => clearInterval(generateFakeData);
}, [setMockWsData]);
return (
<TabulatorTable columns={columns} data={mockWsData} options={options} />
);
};
export default App;
【问题讨论】:
-
过滤也会出现类似的问题,其中每个 updateOrAddData() 请求都会忽略 setFilter() 设置的过滤器选项。每当我尝试使用 updateOrAddData() 返回的承诺时,滚动条就会重新定位回顶部,类似于上面示例中 setSort() 的作用。
标签: javascript reactjs tabulator