React Hooks 如何将引用值传递给依赖项数组?

How do react hooks reference values passed to the array of dependencies?

假设我有这个组件,带有以下钩子:

function SomeComponent(props) {
useEffect(
    () => {
        //....code
        if (props.propOne === ....) { .... }
        // ...code
        if (props.propTwo === ....) { .... }
    }, 
    [props.propOne]
)

return <Something />

}

上面的钩子会运行

但是请注意,挂钩回调还引用了 pros.propTwo,但实际上并未将其传递给依赖项数组。

虽然 props.propTwo 永远不会考虑挂钩是否重新执行,但挂钩回调在其主体中引用的值会发生什么变化?

例如

钩子引用值是基于在组件执行时创建的闭包,还是 React 做了一些巫术,它只保留传递给依赖项数组的值的更新值?

来自文档:

The array of dependencies is not passed as arguments to the callback. Conceptually, though, that’s what they represent: every value referenced inside the callback should also appear in the dependencies array.

更新:

在问完这个问题后,我陷入了丹·阿布拉莫夫 (Dan Abramov) 的这篇文章:

https://overreacted.io/a-complete-guide-to-useeffect/

推荐大家阅读

React hooks 严重依赖 closures 来使用值。挂钩中引用的值将是上次调用 useEffect 时闭包中存在的值。

例如,在您的示例中,如果 props.propOne 发生更改,并且在后续渲染中 props.propTwo 发生更改,则 useEffect 回调中 props.propTwo 的值将之前的值,因为在 props.propTwo 更改时不会执行 useEffect。

但是,如果您同时更新 props.propOneprops.propTwo,则 useEffect 挂钩中的值将是更新后的值。

考虑到 props.propOneprops.propTwo 一起更改并触发渲染的情况,props.propTwo 的值将是 D inside useEffect回调