简体   繁体   English

我如何查看 React 中哪些 props 发生了变化?

[英]How do I see what props have changed in React?

I am looking to make some performance improvements to my React components.我希望对我的 React 组件进行一些性能改进。

If I have a component that is called like:如果我有一个名为的组件:

    <MyComponent
        anObject={someObject}
        aFn={someFn}
        aValue={value}
    />


React will only "re-render" that component if anObject , aFn , or aValue has changed.如果anObjectaFnaValue发生变化,React 只会“重新渲染”该组件。 If I know my function is re-rendering, how can I tell which of those three props caused it?如果我知道我的函数正在重新渲染,我怎么知道这三个 props 中的哪个导致了它?

I know I can console.log aValue and see if it changes, but what about the object and the function.我知道我可以console.log aValue并查看它是否发生变化,但是对象和函数呢。 They can have the same values but be referencing different memory.它们可以具有相同的值但引用不同的内存。 Can I output the memory location?我可以输出内存位置吗?

You can use a useEffect hook for each prop:您可以为每个道具使用useEffect钩子:

const MyComponent = ({ anObject, aFn, aValue }) => {
    React.useEffect(() => {
        console.log('anObject changed');
    }, [anObject]);

    React.useEffect(() => {
        console.log('aFn changed');
    }, [aFn]);

    React.useEffect(() => {
        console.log('aValue changed');
    }, [aValue]);

    // Your existing component code...
};

When the component mounts all three effects will run, but after that the logs will reveal what specifically is changing.当组件安装时,所有三个效果都会运行,但之后日志将显示具体发生的变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM