![](/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.