【发布时间】:2020-11-17 19:35:02
【问题描述】:
我正在尝试使用 React 备忘录组件作为行从头开始创建一个 Table 组件,以防止不必要的重新渲染。 行单元格是从以行数据、行 ID、行索引和 commitChange 函数作为参数的子函数创建的 React 组件数组。 commitChange 函数用于从一行设置 Table 状态。 这是代码:
<Table data={[{name: 1}, {name: 2}]}>
{({data, index, id, commitChange})=>
[
<div>Name: {data.name}</div>,
<TextBox value={data.name} onChange={(value)=>commitChange('name', parseInt(value, 10))}/>,
<TextBox value={data.place}/>
]
}
</Table>
TableComponents.jsx
export const Table = ({ data: initialData, maxRows = 10, children: makeChildren, primaryKey = 'ID' }) => {
const [TableData, setTableData] = useState(initialData);
console.log('table re-render')
useEffect(() => {
console.log('--->table data', TableData)
}, [TableData]);
useEffect(() => {
setTableData(initialData)
}, [initialData]);
const renderCells = useCallback((param) => {
return makeChildren(param)
}, [])
const commitChange = useCallback((field, value, index) => {
setTableData(prevTableData => {
const newState = Array.from(prevTableData)
newState[index][field] = value
return [...newState]
})
}, [])
const renderRows = () => {
return TableData.map((row, i) =>
<TableRow
key={row[primaryKey]}
index={i}
rowData={row}
cells={renderCells}
id={row[primaryKey]}
updateTableData={commitChange}
/>
)
}
//
return (
<table>
<tbody>
{
renderRows()
}
</tbody>
</table>
);
}
const TableRow = React.memo(({ index, rowData, cells, id, updateTableData }) => {
console.log('render row' + index, rowData)
useEffect(() => {
console.log('row ' + index + ' data', rowData)
}, [rowData])
const renderCells = () => {
return cells({ data: rowData, index, id, commitChange: (field, value) => updateTableData(field, value, index) }).map((c, i) => {
return (
<td key={i}>
{c}
</td>
)
})
}
return (
<tr>
{renderCells()}
</tr>
)
})
当一个元素被添加到 Table 组件上的数据道具时,表格会重新渲染并仅渲染添加的行,这可以正常工作。
但是,当从第二个单元格中的文本框编辑行元素时,父表组件上的数据已正确更新,但行不会重新呈现。 当我使用 React.memo areEqual 函数 (Documentation here) 检查传递给组件的前一个和下一个属性时,数据属性是相同的。 当 TableData 逐行更新并且执行了 renderRows 函数但没有重新渲染更新的行时,表格组件会重新渲染。
有什么问题?感谢您的帮助
P.S 不,我不希望外部库制作自定义表格元素
【问题讨论】:
标签: javascript reactjs react-memo