在 useEffect 中,不提供依赖数组和提供空数组有什么区别? [英] In useEffect, what's the difference between providing no dependency array and an empty one?
问题描述
我认为 useEffect
钩子在每次渲染后运行,如果提供了一个空的依赖数组:
I gather that the useEffect
Hook is run after every render, if provided with an empty dependency array:
useEffect(() => {
performSideEffect();
}, []);
但是这和下面的有什么区别?
But what's the difference between that, and the following?
useEffect(() => {
performSideEffect();
});
注意末尾缺少 []
.linter 插件不会发出警告.
Notice the lack of []
at the end. The linter plugin doesn't throw a warning.
推荐答案
不太一样.
给它一个空数组就像
componentDidMount
一样,它只运行一次.
Giving it an empty array acts like
componentDidMount
as in, it only runs once.
不给它第二个参数作为 componentDidMount
和 componentDidUpdate
,因为它首先在挂载时运行,然后在每次重新渲染时运行.
Giving it no second argument acts as both componentDidMount
and componentDidUpdate
, as in it runs first on mount and then on every re-render.
给它一个数组作为第二个参数,其中包含任何值,例如 , [variable1]
只会在挂载时执行 useEffect
钩子中的代码一次,以及每当该特定变量(变量 1)发生变化时.
Giving it an array as second argument with any value inside, eg , [variable1]
will only execute the code inside your useEffect
hook ONCE on mount, as well as whenever that particular variable (variable1) changes.
您可以在 https://reactjs.org/docs/hooks-effect.html
这篇关于在 useEffect 中,不提供依赖数组和提供空数组有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!