react自定义hooks解决内存泄漏

销毁组件时,报警告:

 

解决:

  utils/hooks.ts

export const useFetchState = (...props: any) => {
  const focus = useRef<any>(null);
  const [state, setState] = useState(...props);
  useEffect(() => {
    focus.current = true;
    return () => (focus.current = false);
  }, []);
  const setFetchState = useCallback((...params) => {
    focus.current && setState(...params);
  }, []);
  return [state, setFetchState];
}

  组件中使用useFetchState替代useState

    import { useFetchState } from '@/utils/hooks'

  // const [yearOption, setYearOption] = useState<any[]>([]) // 学年options
  // const [monthOption, setMonthOption] = useState<any[]>([]) // 月options
  const [yearOption, setYearOption] = useFetchState([]) // 学年options
  const [monthOption, setMonthOption] = useFetchState([]) // 月options

 

posted @ 2022-04-26 11:17  吴小明-  阅读(353)  评论(0编辑  收藏  举报