最近我在同事的 React 代码中看到了一些将 setter 函数传递到钩子(Hook)依赖数组中的示例,我觉得它看起来不正确。例如:
const MyComponent = () => {
const [loading, setLoading] = useState(true);
useEffect(() => {
doSomeBigLongNetworkRequest();
setLoading(false);
}, [setLoading, /* other deps */]);
// ...
}
我的感觉是他们误解了依赖数组的目的,据我了解,它是为了指示要监视哪些状态,以便在它们发生变化时钩子(Hook)可以再次触发,而不是简单地表明钩子(Hook)需要使用 setLoading
功能。自从setLoading
函数实际上永远不会改变,将它包含在依赖项中什么都不做。我是正确的,还是在数组中包含 setter 是否有意义?我的另一个想法是,也许这只是一个 linter 错误,因为 linter 无法识别该函数是一个 setter,并认为它可能会改变。
我还应该补充一点,在我见过的实例中,它们包含了 setter,但没有包含变量。所以在上面的例子中,
setLoading
,但不是 loading
将在依赖数组中,并且钩子(Hook)实际上不需要 loading
的值.
最佳答案
是的,你是对的,没有必要根据 docs 包含它们。 :
React guarantees that setState function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.
一般来说,再次基于文档的建议是:
all values from the component scope (such as props and state) that change over time and that are used by the effect should be in dependencies
否则,代码将引用以前渲染中的陈旧值。
关于javascript - 你应该将 setter 函数传递到 React 钩子(Hook)的依赖数组中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65941767/