如何将 Firebase onAuthStateChange 与新的 React Hooks 结合使用? [英] How do I use the Firebase onAuthStateChange with the new React Hooks?

查看:13
本文介绍了如何将 Firebase onAuthStateChange 与新的 React Hooks 结合使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Firebase 为我的应用程序验证用户.我已经创建了 SignInSignUp 表单,并且可以成功创建新用户并使用存储的用户登录.然而,问题在于在 Reload 后保持用户登录状态.

I am using Firebase to authenticate users for my application. I have created the SignIn and SignUp forms and can successfully create new users and sign in with stored users. However the issue comes with maintaining the user logged in state after a Reload.

我在教程中看到的方法是使用如下所示的 HOC 来检查当前用户是否已登录.

The way I have seen it done in tutorials is to use a HOC like the following to check if the current user is logged in.

const withAuthentication = Component => {
  class WithAuthentication extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        authUser: null,
      };
    }

    componentDidMount() {
      this.listener = this.props.firebase.auth.onAuthStateChanged(
        authUser => {
          authUser
            ? this.setState({ authUser })
            : this.setState({ authUser: null });
        },
      );
    }

    componentWillUnmount() {
      this.listener();
    }

    render() {
    return (
      <AuthUserContext.Provider value={this.state.authUser}>
        <Component {...this.props} />
      </AuthUserContext.Provider>
      );
    }
  }

  return withFirebase(WithAuthentication);
};

export default withAuthentication;

然而,我希望使用新的 React Hooks 来消除对 HOCs 的需求.我已经删除了 withFirebase() HOC 通过使用 React ContextuseContext(FirebaseContext) 来访问一个Firebase 的单个实例.有没有办法使用新的 hooks 在我创建的 components 中模仿这个 withAuthentication HOC ?

However I am looking to use the new React Hooks to remove the need for HOCs. I have already removed the withFirebase() HOC by using the React Context and useContext(FirebaseContext) to access a single instance of Firebase. Is there a way using the new hooks to mimic this withAuthentication HOC within components that I create?

我正在使用本教程

https://www.robinwieruch.de/complete-firebase-authentication-反应教程/

标题为使用高阶组件进行会话处理"的部分包含此部分.

The section titled "Session Handling with Higher-Order Components" contains this part.

谢谢!

推荐答案

您可以编写一个 Custom Hook 来注册一个效果并返回 auth 状态

You can write a Custom Hook which registers an effect and returns the auth state

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

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

    return authUser
}

export default useFirebaseAuthentication;

并且在任何Component中你都可以像

and in any Component you can use it like

const MyComponent = (props) => {
   const firebase = useContext(FirebaseContext);
   const authUser = useFirebaseAuthentication(firebase);
   
   return (...)
}

Index.jsx 将包含此代码

ReactDOM.render( 
   <FirebaseProvider> 
      <App /> 
   </FirebaseProvider>, 
   document.getElementById('root')); 

这个 Firebase Provider 是这样定义的,

This Firebase Provider is defined like this,

import Firebase from './firebase';

const FirebaseContext = createContext(); 
export const FirebaseProvider = (props) => ( 
   <FirebaseContext.Provider value={new Firebase()}> 
      {props.children} 
   </FirebaseContext.Provider> 
); 

这篇关于如何将 Firebase onAuthStateChange 与新的 React Hooks 结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆