道具不变时的Granchild渲染

时间:2020-03-30 12:14:13

标签: javascript reactjs react-hooks

我正在使用react功能组件以渲染3个级别的组件。 孩子因祖父母传递的道具而de悔。 在下面的示例中,即使仅props.child1正在更新,Child2仍保持渲染。 有什么方法可以避免在props.child2值从未更改的情况下呈现Child2?这种情况下的最佳实践是什么?

我没有使用redux和onlu钩子。

 const Prandparent = () => {
return (
    <Parent child1={props.child1}
        child2={props.child2} />
 )

};

const Parent = () => {
        return (
            <div>
                <Child1 reportElasticLog={props.child1} />
                <Child2 reportElasticLog={props.child2} />
            </div>
         );
    };

谢谢

1 个答案:

答案 0 :(得分:0)

您需要将React.memo添加到这些组件https://reactjs.org/docs/react-api.html#reactmemo

要小心,并按照PureComponent的注释(类似),将React.memo添加到组件的整个子树中:https://reactjs.org/docs/react-api.html#reactpurecomponent

setTest