从 table 开始添加或删除时,React 备忘录重新呈现后续 table 行

React memo rerenders subsequent table rows when adding or deleting from table start

我有一个 table,其中每一行都在 React.memo 内。在那个 memoized 组件中,我有自定义函数比较器。但是每次我向 table 开头添加行,或从开头删除行时,table 都会重新呈现每一行。

示例: 将行添加到 table end => 一切正常,没有额外的重新渲染。将行添加到 table 开始 => 每行重新呈现其内容。

我希望我的备忘录在删除一行时不重新呈现每一行 table。

Table行码:

const RowMemo = React.memo(({ row, rowIndex }) => {
  console.log('RowMemo renders');
  return <tr key={row.id} className="tr">
{"some contents"}
  </tr>
}, function compare(prev, next) {
  let keysToCompare = ['row', 'rowIndex']

  let isSame = true
  let diffKeys = []
  for (let key of keysToCompare) {
    if (prev[key] != next[key]) {
      diffKeys.push(key)
      // console.log('diff key', key) // shows that only row differs
    }
  }
  if (diffKeys.length) {
    isSame = false;
  }

  if (!isSame)
    console.log('isSame', isSame, prev.row == next.row, prev.row.id, next.row.id); // different rows, that's why it re-renders. 

  return isSame;
})

行呈现简单明了:

myRows.map((row, rowIndex) =>
                  <RowMemo {...{ row, rowIndex }} />
                )

删除一行也简单明了:

function removeTableProgramFormList(e, row) {
    setTableProgramFormList(prevState => prevState.filter(row => row != row));
  }

您应该将 key 属性 添加到更高一级,在其中迭代并呈现 RowMemo 组件。

myRows.map((row, rowIndex) =>
                  <RowMemo key={row.id} {...{ row, rowIndex }} />
                )