使用useCallback重构useEffect挂钩-React

时间:2020-02-22 14:23:18

标签: reactjs

仪表板组件:

const [breadcrumbs, setBreadcrumbs] = useState<Crumb[]>([]);

const handleCrumbs = (data: Crumb[]) => {
  setBreadcrumbs(data);
};

return (
  <>
    <Breadcrumbs crumbsArray={breadcrumbs} />
    <Route
      path={`${path}/partners`}
      render={() => <Partners crumbs={handleCrumbs} />}
    />
  </>
);

合作伙伴组件:

const Partners: React.FC<any> = ({ crumbs }) => {
  useEffect(() => {
    const arr = [1, 2, 3, 4, 5];
    crumbs(arr);
  }, []);
}

出现错误:

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

如何使用useCallback重构它?我可以禁用eslint错误,一切都会按预期进行,但是如何以“正确的方式”做到这一点?

其背后的逻辑是,当安装合作伙伴组件时,我在父组件-仪表板中设置面包屑项。

更新1

仪表板:

const handleCrumbs = useCallback((data: Crumb[]) => {
  setBreadcrumbs(data);
}, []);

合作伙伴:

const Partners: React.FC<any> = ({ crumbs }) => {
  useEffect(() => {
    const arr = [1, 2, 3, 4, 5];
    crumbs(arr);
  });
}

1 个答案:

答案 0 :(得分:2)

handleCrumbs包装在useCallback中,然后将crumbs添加到依赖项数组将是安全的,因为引用永远不会改变。

如果没有useCallback,它将以无限循环结束,因为在每次重新渲染时,crumbs的引用都会改变

仪表板

const handleCrumbs = useCallback((data: Crumb[]) => {
  setBreadcrumbs(data);
}, []);

合作伙伴

const Partners: React.FC<any> = ({ crumbs }) => {
  useEffect(() => {
    const arr = [1, 2, 3, 4, 5];
    crumbs(arr);
  }, [crumbs]);
}

此外,许多人不愿意使用React.FC,而只是在需要时直接输入children,则可以详细了解here