React 钩子 useEffect 仅在更新时? [英] React hooks useEffect only on update?

查看:31
本文介绍了React 钩子 useEffect 仅在更新时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们想限制useEffect只在组件挂载时运行,我们可以在[]中添加useEffect的第二个参数.

If we want to restrict useEffect to run only when the component mounts, we can add second parameter of useEffect with [].

useEffect(() => {
  // ...
}, []);

但是我们怎样才能让useEffect只在组件更新的那一刻运行,除了初始挂载之外?

But how can we make useEffect to run only when the moment when the component is updated except initial mount?

推荐答案

如果您希望 useEffect 仅在除初始安装之外的更新上运行,您可以使用 useRef 来跟踪 initialMountuseEffect 不带第二个参数.

If you want the useEffect to run only on updates except initial mount, you can make use of useRef to keep track of initialMount with useEffect without the second parameter.

const isInitialMount = useRef(true);

useEffect(() => {
  if (isInitialMount.current) {
     isInitialMount.current = false;
  } else {
      // Your useEffect code here to be run on update
  }
});

这篇关于React 钩子 useEffect 仅在更新时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆