[英]Best way to resolve react-hooks/exhaustive-deps warning
Consider this contrived code snippet.考虑这个人为的代码片段。
const foo = () => {return 1;}
const bar = useMemo(() => {return foo();}, [foo])
When I trigger a react-hooks/exhaustive-deps warning, I'll get a message like this.当我触发 react-hooks/exhaustive-deps 警告时,我会收到这样的消息。
The 'foo' function makes the dependencies of useMemo Hook (at line 2) change on every render. Move it inside the useMemo callback. Alternatively, wrap the definition of 'foo' in its own useCallback() Hook.
The warning gives me 2 recommendations: 1) bring foo
inside of bar
's useMemo callback, or 2) wrap the function inside a useCallback.该警告给了我 2 条建议:1) 将
foo
放入bar
的 useMemo 回调中,或 2) 将函数包装在 useCallback 中。
I could certainly do either.我当然可以。 I'm just wondering: Is either of those options preferable over the other, and if so then why?
我只是想知道:这些选项中的任何一个是否比另一个更可取,如果是,那为什么? And if your answer is "it depends", what exactly does it depend on?
如果您的答案是“视情况而定”,那么它究竟取决于什么?
Both ways work just fine.两种方式都工作得很好。 The preference is based on the code and what you are doing with them.
偏好是基于代码和你用它们做什么。
For instance, if you use foo
in more than that one location, then moving it inside the useMemo
callback wouldn't work.例如,如果您在不止一个位置使用
foo
,那么将它移动到useMemo
回调中是行不通的。
If you are only using foo
in the useMemo callback, then it makes sense to define it in there.如果您只在 useMemo 回调中使用
foo
,那么在那里定义它是有意义的。
In that case, it would look something like:在这种情况下,它看起来像:
const bar = useMemo(() => {
const foo = () => 1;
return foo();
// include foo's dependencies in the deps array
}, []);
or you could define it inline:或者您可以内联定义它:
const bar = useMemo(() => {
return 1;
// include foo's dependencies in the deps array
}, []);
With useEffect how I like to resolve this is having a cleanup function使用 useEffect 我喜欢解决这个问题的是有一个清理功能
const [mounted, setMounted] = useState(true);
useEffect(()=>{
if (mounted){
buzz();
}
//Cleanup function
return ()=>{
setMounted(false);
}
}, [mounted]) //hook dependency
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.