【问题标题】:Firebase and ReactJS - Authentication Using Local StorageFirebase 和 ReactJS - 使用本地存储进行身份验证
【发布时间】:2018-02-04 18:56:52
【问题描述】:

我想使用 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;

【问题讨论】:

  • 除了使用本地存储,您还可以将用户的状态存储在您的最高级别组件(如路由器)中。然后你可以使用上下文将它传递给你想要的任何组件。
  • 嗨,谢谢。所以我认为这个 withAuthentication.js 是我最高级别的组件。一旦页面被加载并且我四处导航就很好了。但是当我刷新页面时,需要一秒钟才能确定用户是否登录......我希望这有意义吗?
  • 请不要依赖破解 localStorage。我可以 100% 保证 Firebase Auth 将迁移到 indexedDB。
  • 您不应诉诸这些与内部实施相关的黑客行为,因为 Firebase 身份验证团队保留更改其内部结构的权利。
  • 你会推荐什么来代替 bojeil?

标签: reactjs firebase firebase-authentication


【解决方案1】:

简单,只需替换:

this.setState(() => ({ authUser }))

localStorage.setItem('authUser', JSON.stringify(authUser))

localStorage.removeItem('authUser')

删除它

然后你就可以阅读了:

JSON.parse(localStorage.getItem('authUser'))

而不是 this.state.authUser

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

【讨论】:

  • 非常感谢。我应该两者都做,还是应该只做 localStorage?最佳做法是什么?再次感谢,我现在正在尝试,一旦我知道它对我有用,我会接受!
  • 如果你使用 Redux,你应该将它存储在 localStorage 和 Redux store 中,并且你总是从 Redux store 中读取它,但是为了持久性你也将它保存在 localStorage 中,因为一旦你刷新了Redux 商店不见了。因此,您可以使用 store.subsribe() 使用本地存储中的数据启动 Redux 存储。
  • 但是如果你不是,你不需要在这个高阶组件中同时使用,你最好只使用 localStorage
  • 谢谢 Arber,我已经做到了,而且似乎确实更快。但是,localStorage 现在似乎有点落后了。例如,当我注销时,在页面刷新之前什么都不会发生。如果我使用 localStorage 而不是不使用,我是否需要向我的 withAuthentication 组件添加任何东西来处理这个问题(我之前没有遇到过这个问题)。
  • 好的,谢谢!我已经在原始 setState 代码旁边实现了 localStorage 方法 - 再次感谢!
猜你喜欢
  • 2018-12-06
  • 2020-12-16
  • 2021-07-30
  • 2021-03-11
  • 2020-10-09
  • 2017-03-11
  • 2020-10-22
  • 2019-03-28
  • 2018-10-19
相关资源
最近更新 更多