javascript - 为什么useEffect没有被调用,当props改变时,render被调用?

标签 javascript reactjs

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

const { block } = props;

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

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

const { block } = props;

const inputRef = useRef(null);

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

最佳答案

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

Here is a reference from the official docs

关于javascript - 为什么useEffect没有被调用,当props改变时,render被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59493868/

相关文章:

javascript - 如何从 div 复制所有内容 (<p><strong>) 并粘贴到模式中

node.js - SPA 与 Deepstream.io 用于登录页面的 HTTP 身份验证

javascript - 是否可以使用 material ui 选项卡并仍然使用 react router?

javascript - 从 react-router-dom 属性 'sumParams' 升级版本 4 useParams () 后 TypeScript 错误在类型 '{}' 上不存在

reactjs - React.SFC 给出 Element vs ReactElement<any> 错误,ValidationMap

reactjs - 在 nginx 中使用 certbot 的问题

javascript - 通过 anchor 标签添加幻灯片效果

javascript - Metro 应用程序可以在不打开页面的情况下打开默认浏览器吗?

javascript - fullcalendar 不显示基于事件时间的事件

javascript - 如果输入 type=text 有重复条目,如何更改 CSS