ReactJS lifecycle method inside a function Component

前端 未结 8 545
一生所求
一生所求 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:17

    You can make use of create-react-class module. Official documentation

    Of course you must first install it

    npm install create-react-class
    

    Here is a working example

    import React from "react";
    import ReactDOM from "react-dom"
    let createReactClass = require('create-react-class')
    
    
    let Clock = createReactClass({
        getInitialState:function(){
            return {date:new Date()}
        },
    
        render:function(){
            return (
                <h1>{this.state.date.toLocaleTimeString()}</h1>
            )
        },
    
        componentDidMount:function(){
            this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
        },
    
        componentWillUnmount:function(){
            clearInterval(this.timerId)
        }
    
    })
    
    ReactDOM.render(
        <Clock/>,
        document.getElementById('root')
    )
    
    0 讨论(0)
  • 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]);
    };  
    
    0 讨论(0)
提交回复
热议问题