繁体   English   中英

React Hook useCallback 缺少依赖项警告,但存在依赖项

[英]React Hook useCallback has a missing dependency warning, but the dependencies are present

我有以下几点:

props = {
onPositive: () => void;
closeFunc: () => void;
... about 5 more props
}

使用以下钩子:

const onPositive: () => void = useCallback(() => {
        props.positionFunc();
        props.closeFunc();
    }, [props.positionFunc, props.closeFunc]);

我收到此警告:

React Hook useCallback has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the useCallback call and refer to those specific props inside useCallback 

根据我在DependencyList 中的理解,我应该包含回调所具有的依赖项,我是否遗漏了什么?

我可以通过为DependencyList放置[props]来关闭警告,但我认为不需要?

有人能解释一下为什么我应该放道具而不是我拥有的东西吗?

关于如何解决这个问题,警告非常明确:

然而,'props' 会在任何 props 改变时改变,所以首选的解决方法是在 useCallback 调用之外解构 'props' 对象并在 useCallback 中引用那些特定的 props

所以修复将是:

const {positionFunc, closeFunc} = props;

const onPositive: () => void = useCallback(() => {
       positionFunc();
       closeFunc();
    }, [positionFunc, closeFunc]);

这是预期的行为。 道具本身被传递下来,因此可能会看到陈旧的价值。 这是对这些信息的引用,并有明确的解释,

这里是响应的链接https://github.com/facebook/react/issues/16265#issuecomment-517518539

截图供参考, 在此处输入图片说明

PS:我无法在评论中提供所有这些信息,因为已经有答案了。 但是,我认为它有助于添加更多信息,从而提供额外的答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM