react自定义hooks解决内存泄漏


销毁组件时,报警告:

解决:

  utils/hooks.ts

export const useFetchState = (...props: any) => {
  const focus = useRef(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([]) // 学年options
  // const [monthOption, setMonthOption] = useState([]) // 月options
  const [yearOption, setYearOption] = useFetchState([]) // 学年options
  const [monthOption, setMonthOption] = useFetchState([]) // 月options