反应避免所有子项重新呈现

时间:2020-05-20 16:23:07

标签: reactjs react-hooks

因此,我有一个包含多个子级的主组件,我在下面的示例中对其进行了简化

const Master = ({ c1props, c2props }) => {
    const [count, setCount] = useState(0)

    return <div>
        <div>{count}</div>
        <Child {...c1props}/>
        <Child {...c2props}/>
    </div>
}

因此,这里的问题是,当我仅更新状态“ count”时,组件将重新呈现,这是一个问题,因为它们很重。 我当时正在考虑在Child中使用useMemo()来避免那些不需要的重新渲染,但是我不建议这样做。 知道如何解决这个问题吗?

谢谢

2 个答案:

答案 0 :(得分:1)

const MemoizedChild1 = React.memo(Child1, isEqual);
const MemoizedChild2 = React.memo(Child2, isEqual);

然后您像这样使用它:

const Master = ({ c1props, c2props }) => {
    const [count, setCount] = useState(0)

    return <div>
        <div>{count}</div>
        <MemoizedChild1 {...c1props}/>
        <MemoizedChild2 {...c2props}/>
    </div>
}

其中isEqual是一个lodash函数,可以深入测试道具的相等性。

通常,您可以使用如下备忘录:

function MyComponent(props) {
  /* render using props */
}
function areEqual(prevProps, nextProps) {
  /*
  return true if passing nextProps to render would return
  the same result as passing prevProps to render,
  otherwise return false
  */
}
export default React.memo(MyComponent, areEqual);

进一步了解the docs

useMemo是一个用于记忆值的钩子,备忘录可以让您控制何时呈现组件。

答案 1 :(得分:1)

如果您想避免使用备忘录,则可以考虑拆分主数据,并创建另一个包含计数状态的Counter组件:

const Master = ({ c1props, c2props }) => (
  <div>
    <Counter />
    <Child {...c1props}/>
    <Child {...c2props}/>
  </div>
)