React 自定义hook 解决Can't perform a React state update on an unmounted component.

481 阅读1分钟

在react开发中经常会经常会碰到这种警告:Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

原因呢谁都知道在已卸载的组件上执行setState,解决方案有很多,在卸载的时候对所有的操作进行清除、增加一个标记页面卸载的时候重置这个标记等等。

这些解决方案都能解决这个问题,但对于我来说不是最好的解决方案,或者说不是我想要的解决方案,分享一个我的解决方案,拥抱hooks

import {useCallback, useEffect, useRef, useState} from 'react';

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

使用也很方便

 const [state, setState] = useState('test');
  //替换为
 const [state, setState] = useFetchState('test');

原理我在这就不多做赘述了,就是一个思路的问题