Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

reactjs - Is there a way that I can use a custom hook in a class-based component?

I have this hook:

import { useEffect, useState } from 'react';
import { auth } from "../firebase/auth-service"

const useFirebaseAuthentication = () => {
   const [authUser, setAuthUser] = useState(null);

   useEffect(() => {
       const unlisten = auth.onAuthStateChanged(
           authUser => {
               authUser
                   ? setAuthUser(authUser)
                   : setAuthUser(null);
           },
       );
       return () => {
           unlisten();
       }
   });

   return authUser
}

export default useFirebaseAuthentication;

That I use like this:

const authUser = useFirebaseAuthentication();

Is there a way I could use this hook useFirebaseAuthentication() in a class-based component?

question from:https://stackoverflow.com/questions/65843692/is-there-a-way-that-i-can-use-a-custom-hook-in-a-class-based-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Class based components directly donot support Hooks.

Read React-FAQ

You can create a Higher Order Component, like this:

import React from 'react';
import { useFirebaseAuthentication} from '../hooks/useFirebaseAuthentication';

export const withFireBaseAuthHookHOC = (Component: any) => {
  return (props: any) => {
    const authUser = useFirebaseAuthentication();

    return <Component authUser ={authUser} {...props} />;
  };
};

Now just wrap your class based component with this HOC.

.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...