[英]Refactor useEffect hook with useCallback - React
Dashboard component:仪表板组件:
const [breadcrumbs, setBreadcrumbs] = useState<Crumb[]>([]);
const handleCrumbs = (data: Crumb[]) => {
setBreadcrumbs(data);
};
return (
<>
<Breadcrumbs crumbsArray={breadcrumbs} />
<Route
path={`${path}/partners`}
render={() => <Partners crumbs={handleCrumbs} />}
/>
</>
);
Partners component:合作伙伴组件:
const Partners: React.FC<any> = ({ crumbs }) => {
useEffect(() => {
const arr = [1, 2, 3, 4, 5];
crumbs(arr);
}, []);
}
There i'm getting an error:我收到一个错误:
React Hook useEffect has a missing dependency: 'crumbs'. Either include it or remove the dependency array. If 'crumbs' changes too often, find the parent component that defines it and wrap that definition in useCallback react-hooks/exhaustive-deps
How can i refactor this with useCallback?如何使用 useCallback 重构它? I can just disable eslint error and everything would work as expected, but how to do that in a "right way"?
我可以禁用 eslint 错误,一切都会按预期工作,但是如何以“正确的方式”做到这一点?
Logic behind this, is when Partners component is mounted, i'm setting breadcrumb items in the parent component - Dashboard.这背后的逻辑是,当 Partners 组件安装时,我在父组件 - 仪表板中设置面包屑项目。
UPDATE 1更新 1
Dashboard:仪表盘:
const handleCrumbs = useCallback((data: Crumb[]) => {
setBreadcrumbs(data);
}, []);
Partners:伙伴:
const Partners: React.FC<any> = ({ crumbs }) => {
useEffect(() => {
const arr = [1, 2, 3, 4, 5];
crumbs(arr);
});
}
Wrap handleCrumbs
in useCallback
and then it will be safe to add crumbs
to the dependencies array because the reference will never change.将
handleCrumbs
包装在useCallback
,然后将crumbs
添加到依赖项数组将是安全的,因为引用永远不会改变。
without useCallback
it will end up in an infinite loop because on every re-render the reference of crumbs
will change没有
useCallback
它将以无限循环结束,因为在每次重新渲染时, crumbs
的引用都会改变
Dashboard仪表盘
const handleCrumbs = useCallback((data: Crumb[]) => {
setBreadcrumbs(data);
}, []);
Partners伙伴
const Partners: React.FC<any> = ({ crumbs }) => {
useEffect(() => {
const arr = [1, 2, 3, 4, 5];
crumbs(arr);
}, [crumbs]);
}
Also, a lot of people prefer not to use React.FC
and just type children
explicitly if you need them, you can read more about it here此外,很多人不喜欢使用
React.FC
并且只在需要时明确输入children
,您可以在此处阅读更多相关信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.