Firebase 和 ReactJS - 使用本地存储进行身份验证

use*_*620 1 firebase reactjs firebase-authentication

我想使用 localstorage 来保持身份验证状态,以避免刷新时页面内容变慢。我在其他地方读过这个,但不确定如何在我的情况下实施。谁能帮我弄清楚如何编辑下面的内容以使其正常工作?

这个例子很相似,但我不确定如何将它应用到我的案例中。

import React from 'react';
import { firebase } from '../firebase';
import PropTypes from 'prop-types';

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

      this.state = {
        authUser: null,
      };


    }

    getChildContext() {
      return {
        authUser: this.state.authUser,
      };
    }

    componentDidMount() {
      firebase.auth.onAuthStateChanged(authUser => {
        authUser
          ? this.setState(() => ({ authUser }))
          : this.setState(() => ({ authUser: null }));
      });
    }
    render() {
      return (
        <Component />
      );
    }
  }


  WithAuthentication.childContextTypes = {
    authUser: PropTypes.object,
  };

  return WithAuthentication;
}

export default withAuthentication;
Run Code Online (Sandbox Code Playgroud)

Arb*_*ani 5

简单,只需替换:

this.setState(() => ({ authUser }))
Run Code Online (Sandbox Code Playgroud)

localStorage.setItem('authUser', JSON.stringify(authUser))
Run Code Online (Sandbox Code Playgroud)

或者

localStorage.removeItem('authUser')
Run Code Online (Sandbox Code Playgroud)

删除它

然后你可以阅读它:

JSON.parse(localStorage.getItem('authUser'))
Run Code Online (Sandbox Code Playgroud)

而不是this.state.authUser

并在 componentDidMount 再次调用之前检查 localStorage.getItem('authUser') 是否存在。