React教程(八) : 自定义Hook

示例1:useMounted

export const useMounted = () => {
  const isMounted = useRef<boolean>(false);

  useEffect(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
    };
  }, []);

  return isMounted;
};
export const LoginForm: FC = () => {
  const isMounted = useMounted();

  return(
    <Button type="submit" disabled={isLoading} >
            Login
    </Button>
  );
};

示例2:useWindowSize

function useWindowSize() {
  // Initialize state with undefined width/height so server and client renders match
  // Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  });

  useEffect(() => {
    // Handler to call on window resize
    function handleResize() {
      // Set window width/height to state
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }
    
    // Add event listener
    window.addEventListener("resize", handleResize);
    
    // Call handler right away so state gets updated with initial window size
    handleResize();
    
    // Remove event listener on cleanup
    return () => window.removeEventListener("resize", handleResize);
  }, []); // Empty array ensures that effect is only run on mount

  return windowSize;
}

完整的代码示例:
https://usehooks.com/useWindowSize/

示例3:useQueryState
append query parameters to URL's query string
简单实现版本:

export const useQueryState = <T>() => {
  const history = useHistory();
  const location = useLocation();
  const [parsedQuery, setParsedQuery] = useState<T>({} as T);

  useEffect(() => {
    const query = queryString.parse(location.search);
    setParsedQuery((query as unknown) as T);
  }, [location.search]);

  const updateQuery = (update: Partial<T>) => {
    const oldQuery = queryString.parse(location.search);
    const newQuery = { ...oldQuery, ...update };

    // skip history update if old and new queries are the same
    if (!_.isEqual(oldQuery, newQuery)) {
      history.push({
        search: queryString.stringify(newQuery)
      });
    }
  };

  return [parsedQuery, updateQuery] as const;
};

完整代码:
https://github.com/992990831/modernization/tree/main/customhook

复杂的实现版本:
https://www.npmjs.com/package/use-query-state
https://github.com/yuanfux/use-query-state/blob/master/src/useQueryState/index.ts

最后,附上收集了多个custom hook的网站地址:https://usehooks.com/

posted @ 2020-11-06 22:50  老胡Andy  阅读(774)  评论(0编辑  收藏  举报