简体   繁体   English

为什么不调用 useEffect,当 props 发生变化时,会调用 render?

[英]Why useEffect is not called, when props have changed, render is called?

I have useEffect and I don't understand why useEffect is not called, when props have changed, but render is called.我有 useEffect 并且我不明白为什么 useEffect 不被调用,当 props 改变时,但调用了 render 。 I have something like this, 'block' is object:我有这样的东西,“块”是对象:

const { block } = props;

useEffect(() => {
    setTimeout(() => {
        if (inputRef.current) {
            inputRef.current.focus();
        }
    });
}, []);

Thank you for helping!感谢您的帮助! Now, I have next question) My inputRef is null, when block is changed and render is called:现在,我有下一个问题)我的 inputRef 为空,当块更改并调用渲染时:

const { block } = props;

const inputRef = useRef(null);

useEffect(() => {
    setTimeout(() => {
        if (inputRef.current) {
            inputRef.current.focus();
        }
    });
}, [block, inputRef]);
...
<SomeComponent
  inputRef={inputRef}
 />

Because you have no parameters on your useEffect.因为你的 useEffect 没有参数。 If you pass the second parameter as an empty array, it will only fire when the component is mounted.如果您将第二个参数作为空数组传递,它只会在组件安装时触发。

Here is a reference from the official docs 这是官方文档的参考

You can get this behavior by passing a block property as the second parameter in your useEffect function:您可以通过将block属性作为useEffect函数中的第二个参数传递来获得此行为:

const { block } = props;

useEffect(() => {
    setTimeout(() => {
        if (inputRef.current) {
            inputRef.current.focus();
        }
    });
}, [block]);

Don't forget that you can pass more properties:不要忘记你可以传递更多的属性:

useEffect(() => {}, [block, otherProperty])

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

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