ReactJS lifecycle method inside a function Component

前端 未结 8 576
一生所求
一生所求 2020-11-30 19:28

Instead of writing my components inside a class, I\'d like to use the function syntax instead.

How do I override componentDidMount, componentWillM

8条回答
  •  攒了一身酷
    2020-11-30 20:20

    You can make your own "lifecycle methods" using hooks for maximum nostalgia.

    Utility functions:

    import { useEffect, useRef } from "react";
    
    export const componentDidMount = handler => {
      return useEffect(() => {
        return handler();
      }, []);
    };
    
    export const componentDidUpdate = (handler, deps) => {
      const isInitialMount = useRef(true);
    
      useEffect(() => {
        if (isInitialMount.current) {
          isInitialMount.current = false;
    
          return;
        }
    
        return handler();
      }, deps);
    };
    

    Usage:

    import { componentDidMount, componentDidUpdate } from "./utils";
    
    export const MyComponent = ({ myProp }) => {
      componentDidMount(() => {
        console.log("Component did mount!");
      });
    
      componentDidUpdate(() => {
        console.log("Component did update!");
      });
    
      componentDidUpdate(() => {
        console.log("myProp did update!");
      }, [myProp]);
    };  
    

提交回复
热议问题