ReactJS lifecycle method inside a function Component

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

    Solution One: You can use new react HOOKS API. Currently in React v16.8.0

    Hooks let you use more of React’s features without classes. Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. Hooks solves all the problems addressed with Recompose.

    A Note from the Author of recompose (acdlite, Oct 25 2018):

    Hi! I created Recompose about three years ago. About a year after that, I joined the React team. Today, we announced a proposal for Hooks. Hooks solves all the problems I attempted to address with Recompose three years ago, and more on top of that. I will be discontinuing active maintenance of this package (excluding perhaps bugfixes or patches for compatibility with future React releases), and recommending that people use Hooks instead. Your existing code with Recompose will still work, just don't expect any new features.

    Solution Two:

    If you are using react version that does not support hooks, no worries, use recompose(A React utility belt for function components and higher-order components.) instead. You can use recompose for attaching lifecycle hooks, state, handlers etc to a function component.

    Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).

    // taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33
    
    function RenderlessComponent() {
      return null; 
    }
    
    export default lifecycle({
    
      componentDidMount() {
        const { checkIfAuthed } = this.props;
        // Do they have an active session? ("Remember me")
        checkIfAuthed();
      },
    
      componentWillReceiveProps(nextProps) {
        const {
          loadUser,
        } = this.props;
    
        // Various 'indicators'..
        const becameAuthed = (!(this.props.auth) && nextProps.auth);
        const isCurrentUser = (this.props.currentUser !== null);
    
        if (becameAuthed) {
          loadUser(nextProps.auth.uid);
        }
    
        const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
        if (shouldSetCurrentUser) {
          const currentUser = nextProps.users[nextProps.auth.uid];
          if (currentUser) {
            this.props.setCurrentUser({
              'id': nextProps.auth.uid,
              ...currentUser,
            });
          }
        }
      }
    })(RenderlessComponent);
    

提交回复
热议问题