简体   繁体   English

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

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

I have the following:我有以下几点:

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

With the following hook:使用以下钩子:

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

I am getting this warning:我收到此警告:

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 

From what I understand in DependencyList I should include the dependencies the callback has, am I missing something?根据我在DependencyList 中的理解,我应该包含回调所具有的依赖项,我是否遗漏了什么?

I can turn-off the warning by putting [props] for DependencyList however I don't think is needed?我可以通过为DependencyList放置[props]来关闭警告,但我认为不需要?

Can somebody explain me why I should put props and not what I have?有人能解释一下为什么我应该放道具而不是我拥有的东西吗?

The waring is pretty explicit about how to fix that:关于如何解决这个问题,警告非常明确:

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

So the fix would be:所以修复将是:

const {positionFunc, closeFunc} = props;

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

This is expected behavior.这是预期的行为。 the props itself is passed down so it may be possible to see stale value.道具本身被传递下来,因此可能会看到陈旧的价值。 Here is the reference to this information with clear explanation,这是对这些信息的引用,并有明确的解释,

Here it the link to the response https://github.com/facebook/react/issues/16265#issuecomment-517518539这里是响应的链接https://github.com/facebook/react/issues/16265#issuecomment-517518539

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

PS: I couldn't provide all this info in a comment, as there is already an answer. PS:我无法在评论中提供所有这些信息,因为已经有答案了。 However, I think it helps add more information and hence the additional answer.但是,我认为它有助于添加更多信息,从而提供额外的答案。

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

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