【问题标题】:Is there a way that I can use a custom hook in a class-based component?有没有办法可以在基于类的组件中使用自定义挂钩?
【发布时间】:2021-04-26 20:00:37
【问题描述】:

我有这个钩子:

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;

我是这样使用的:

const authUser = useFirebaseAuthentication();

有没有办法在基于类的组件中使用这个钩子 useFirebaseAuthentication()?

【问题讨论】:

  • 如果你想知道如何在组件之间共享,看下面的答案stackoverflow.com/questions/65785994/…
  • 类具有相当于钩子的状态。您可以将挂钩值共享给基于类的组件,但它们应该具有父子关系

标签: reactjs firebase react-hooks


【解决方案1】:

基于类的组件直接不支持 Hooks。

阅读React-FAQ

你可以创建一个Higher Order Component,像这样:

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} />;
  };
};

现在只需使用 HOC 包装基于类的组件。

.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-23
    • 2023-01-26
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2020-07-26
    • 1970-01-01
    相关资源
    最近更新 更多