为什么不调用useEffect,在更改道具后调用render?

问题描述 投票:0回答:2

我有useEffect,但我不明白为什么在更改道具但调用render时不调用useEffect。我有这样的东西,“块”是对象:

const { block } = props;

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

谢谢您的帮助!现在,我有下一个问题)当更改块并调用render时,我的inputRef为null:

const { block } = props;

const inputRef = useRef(null);

useEffect(() => {
    setTimeout(() => {
        if (inputRef.current) {
            inputRef.current.focus();
        }
    });
}, [block, inputRef]);
...
<SomeComponent
  inputRef={inputRef}
 />
javascript reactjs
2个回答
3
投票

因为您的useEffect没有参数。如果将第二个参数作为空数组传递,则仅在安装组件时才会触发。

Here is a reference from the official docs


1
投票

您可以通过在block函数中传递useEffect属性作为第二个参数来获得此行为:

const { block } = props;

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

不要忘记,您可以传递更多属性:

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

© www.soinside.com 2019 - 2024. All rights reserved.