销毁组件时,报警告:

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