【问题标题】:React.memo not re render if props change如果道具发生变化,React.memo 不会重新渲染
【发布时间】: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


    【解决方案1】:

    问题是你在浅拷贝你的 TableData(使用...)所以当你在这里更新值时:

    newState[index][field] = value
    

    ...您正在改变数组中的项目,但该项目的引用 to 保持不变。一种解决方法是这样做:

    setTableData(prevTableData =>
        prevTableData.map((item, i) =>
          i === index ? { ...item, [field]: value } : item,
        ),
      )
    

    所以现在更新字段时会创建一个新对象。

    【讨论】:

    • 谢谢,你让我开心(修复了凌晨 2.25 的错误)
    猜你喜欢
    • 2021-06-21
    • 1970-01-01
    • 2019-12-10
    • 2020-05-28
    • 2019-03-11
    • 2020-10-20
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    相关资源
    最近更新 更多