![](/img/trans.png)
[英]Reduce the size of a large data set by sampling/interpolation to improve chart performance
[英]Improve rendering performance of large table data set
我有一个 nxn 数组,其中包含用于呈现表格单元格的所有数据。
const Table = () => {
const [initData, setInitData] = useState([
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"],
["a", "b", "c", "d", "e", "f", "b", "c", "d", "e", "f"]
]);
const handleChange = e => {
let thisTD = e.target.parentNode;
let cellIndex = thisTD.cellIndex;
let rowIndex = thisTD.parentNode.rowIndex;
let tempArr = [...initData];
tempArr[rowIndex][cellIndex] = e.target.value;
setInitData(tempArr);
};
return (
<>
<table>
<tbody>
{initData &&
initData.map((row, rindex) => (
<tr key={rindex}>
{row.map((cell, cindex) => (
<td key={cindex}>
<textarea value={cell} onChange={handleChange} />
</td>
))}
</tr>
))}
</tbody>
</table>
</>
);
};
问题是,每当一个单元格更改自己的数据时,表格的所有单元格都会重新渲染。
如果单元格数量增加,当用户更改单元格的内容时,这会导致性能下降和滞后。
目前,一切正常,但我想提高性能以实现缩放目的。 每次更改都重新渲染整个表看起来既愚蠢又昂贵,那么我该如何更改数据结构或我的 React 组件呢? 谢谢你的每一个想法!
首先让我们检查一切是否被渲染:
row.map((cell, cindex) => {
console.log([cell, cindex], `rendered`);
return (
<td key={cindex}>
<textarea value={cell} onChange={handleChange} />
</td>
);
});
在每次单元格更改时,都会呈现所有表格。
我们可以使用React.memo
和一些useRef
来修复它来修复关闭问题:
const Entry = ({ value, rindex, cindex, onChange }) => {
console.log([rindex, cindex], 'rendered');
const textRef = useRef();
const $onChange = () => {
onChange(prev => {
let tempArr = [...prev];
tempArr[rindex][cindex] = textRef.current.value;
return tempArr;
});
};
return (
<td>
<textarea ref={textRef} value={value} onChange={$onChange} />
</td>
);
};
const MemoEntry = React.memo(Entry);
const Table = () => {
const [initData, setInitData] = useState([['a', 'b', 'c'], ['a', 'b', 'c']]);
return (
<>
<table>
<tbody>
{initData &&
initData.map((row, rindex) => (
<tr key={rindex}>
{row.map((cell, cindex) => {
return (
<MemoEntry
key={cindex}
rindex={rindex}
cindex={cindex}
value={cell}
onChange={setInitData}
/>
);
})}
</tr>
))}
</tbody>
</table>
</>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.