在道具中传递对象时避免重新渲染孩子

mle*_*ter 6 javascript reactjs react-hooks

假设我有一个像这样的性能优化组件:

const PerformanceComponent = ({style}) => {
     return <View style={style}>...</View>
}

export default React.memo(PerformanceComponent)
Run Code Online (Sandbox Code Playgroud)

我在父级内部使用组件,如下所示:

{someArray.map((style) => (
    <PerformanceComponent style={style} />
)}
Run Code Online (Sandbox Code Playgroud)

我正在为 传递不同的对象style,它看起来像这样:

const styles = {
    width: 200,
    height: 200
}
Run Code Online (Sandbox Code Playgroud)

现在 React.memo 不会成功,因为我正在传递一个对象,而 React 只会比较内存地址(我认为它被称为Shallow Compare)。

即使-object 没有改变,我有哪些选择可以避免不必要的重新渲染PerformanceComponentstyles

Ven*_*sky 3

正如其他答案所说,您需要将一个函数作为第二个参数传递给React.memo该函数,该函数将接收前一个 prop 和当前 prop,以便您可以决定是否应该重新渲染组件(就像shouldComponentUpdate类组件的生命周期一样)。

因为比较整个对象以查看是否有任何更改可能是一项昂贵的操作(取决于对象),并且因为您可以拥有多个属性,所以确保其高效的一种方法是使用 lodash _.isEqual

import { isEqual } from 'lodash'

const PerformanceComponent = ({style}) => {
     return <View style={style}>...</View>
}

export default React.memo(PerformanceComponent, isEqual)
Run Code Online (Sandbox Code Playgroud)

这样你就不必担心实现,isEqual而且它也有很好的性能。