日常学习记录:ahooks里的useSafeState, useGetState的使用场景

2,177 阅读1分钟

场景一:useSafeState:

快速点击切换tab栏,加载组件后会调用接口获取数据、设置state,如果这时候接口还没返回,组件就卸载了,没state可设置了,就会导致内存泄漏

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. 常规解决方法

hooks模式可以使用 ahooks 里的 useSafeState 替换 setState。

内部原理:

var setCurrentState = react_1.useCallback(function (currentState) {
    /** if component is unmounted, stop update */
    if (unmountedRef.current) return;
    setState(currentState);
  }, []);

场景二:useGetState:

组件中有不止一处地方对同一个state进行了setState操作,但有些地方的setState操作之后需要用到state的最新值。用useEffect对这个state进行监听会影响其他的setState。可以使用useRef替换来获取最新值。但这时候会懒得替换,就可以使用 useGetState

const [count, setCount, getCount] = useGetState

getCount()

内部原理:

var stateRef = react_1.useRef(state);
  stateRef.current = state;
  var getState = react_1.useCallback(function () {
    return stateRef.current;
  }, []);
return [state, setState, getState];