使用 useEffect、useRef 和 reducer 应对内存泄漏

时间:2021-01-06 17:30:15

标签: javascript reactjs

我在 React 中有一个非常简单的组件,它尝试首先从 API 获取一些数据,然后读取从父组件传递下来的 prop。我正在使用 useReducer 来管理该组件的状态。除了在组件读取从父级传递的 prop 时调度事件的部分之外,一切似乎都正常工作。
起初,我没有不应该使用 useRef,但经过一番搜索我发现我应该做一些清理工作。控制台的输出表明我有内存泄漏,所以我现在使用 useRef。但是,我仍然收到该错误并且我的组件无法安装。这是我的组件:

function CategoriesTable(props: any) {
  const { newCategory } = props;
  const isMounted = useRef(true);
  const [state, dispatch] = useReducer(
    categoriesReducer,
    Array<CategoriesModel>()
  );

  useEffect(() => {
    getCategories();
  }, []);

  useEffect(() => {
    isMounted.current = true;
    if (isMounted.current) 
      dispatch({ type: "NEW_CATEGORY", payload: newCategory.body });
    return () => {
      isMounted.current = false;
    };
  }, [newCategory]);

  const getCategories = () => {
    axiosInstance
      .get("/categories")
      .then((res: AxiosResponse) => {
          dispatch({ type: "FETCH_CATEGORIES", payload: res.data });
      })
  };

  if (state.length === 0) {
    return (
      <Typography align="center">
        No category has been added! Please click the Create Category button
        above
      </Typography>
    );
  }

  return (
    <TableContainer component={Paper}>
        <TableBody>
          {state.map((category: CategoriesModel, idx: number) => (
            <TableRow key={idx}>
              //{unnecessary code}
            </TableRow>
          ))}
    </TableContainer>
  );
}

我发现问题出在这个 useEffect() 上:

useEffect(() => {
    isMounted.current = true;
    if (isMounted.current) {
      dispatch({ type: "NEW_CATEGORY", payload: newCategory.body });
    }
    return () => {
      isMounted.current = false;
    };
  }, [newCategory]);

当我将其注释掉时,除了依赖于 useEffect() 的功能外,一切都运行良好。我不确定我做错了什么。请你帮助我好吗?另外,我是否应该在另一个 useEffect 中使用 useRef 来防止内存泄漏,尽管它不会提示我潜在的内存泄漏?

谢谢!

0 个答案:

没有答案