React 钩子中的 useEffect 第二个参数变化? [英] useEffect second argument variations in React hook?

查看:51
本文介绍了React 钩子中的 useEffect 第二个参数变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 react hooks 中,这 3 个片段有什么区别.

In react hooks, what is the difference between these 3 snippets.

//1.

function App() {
  const [isOn, setIsOn] = useState(false);

  useEffect(() => {
    const interval = setInterval(() => console.log('tick'), 1000);

    return () => clearInterval(interval);
  });
}

//2.

function App() {
  const [isOn, setIsOn] = useState(false);

  useEffect(() => {
    const interval = setInterval(() => console.log('tick'), 1000);

    return () => clearInterval(interval);
  }, []);
}

//3. 

function App() {
  const [isOn, setIsOn] = useState(false);

  useEffect(() => {
    const interval = setInterval(() => console.log('tick'), 1000);

    return () => clearInterval(interval);
  }, [isOn]);
}

传递空数组、带元素的数组和根本不传递之间的区别?

Difference between passing empty array, array with an element and not passing at all?

推荐答案

第一个将在挂载和状态改变时运行效果.将在状态更改和卸载时调用清理.

The first will run the effect on mount and whenever the state changes. The clean up will be called on state change and on unmount.

第二个只会在挂载时运行一次效果,清理只会在卸载时调用.

The second will only run the effect once on mount and the clean up will only get called on unmount.

最后一个将在挂载和 isOn 状态改变时运行效果.将在 isOn 更改和卸载时调用清理.

The last will run the effect on mount and whenever the isOn state changes. The clean up will be called when isOn changes and on unmount.

在您的示例中,第一个和最后一个示例的行为相同,因为唯一会改变的状态是 isOn.如果第一个示例有更多状态,那么如果另一个状态发生变化,该效果也会重新触发.

In your examples, the first and last examples will behave the same because the only state that will change is isOn. If the first example had more state, that effect would also refire if the other state were to change.

我想我还应该补充一点,事情的顺序是这样的:mount: ->运行效果状态改变:运行清理->运行效果, unmount ->运行清理.

I guess I should also add is that the order of things would be like: mount: -> run effect, state change: run clean up -> run effect, unmount -> run clean up.

这篇关于React 钩子中的 useEffect 第二个参数变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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