浏览器刷新后如何保持React组件状态

jin*_*ma 5 firebase reactjs react-router

谢谢你阅读我的第一个问题.

我尝试auth使用Shared Root使用react,react-router和firebase.所以,我想保持App.js用户状态.但是当我尝试刷新浏览器时,找不到用户状态.

我试图保存到localstorage.但有没有办法在没有浏览器刷新后保持组件状态localStorage


App.js

import React, { Component, PropTypes } from 'react'
import Rebase from 're-base'

import auth from './config/auth'

const base = Rebase.createClass('https://myapp.firebaseio.com')

export default class App extends Component {
  constructor (props) {
    super(props)
    this.state = {
      loggedIn: auth.loggedIn(),
      user: {}
    }
  }

  _updateAuth (loggedIn, user) {
    this.setState({
      loggedIn: !!loggedIn,
      user: user
    })
  }

   componentWillMount () {
     auth.onChange = this._updateAuth.bind(this)
     auth.login() // save localStorage
   }

  render () {
    return (
      <div>
        { this.props.children &&
          React.cloneElement(this.props.children, {
            user: this.state.user
          })
        }
      </div>
    )
  }
}
App.propTypes = {
  children: PropTypes.any
}
Run Code Online (Sandbox Code Playgroud)

auth.js

import Rebase from 're-base'
const base = Rebase.createClass('https://myapp.firebaseio.com')

export default {
  loggedIn () {
    return !!base.getAuth()
  },

  login (providers, cb) {
    if (Boolean(base.getAuth())) {
      this.onChange(true, this.getUser())
      return
    }

    // I think this is weird...
    if (!providers) {
      return
    }

    base.authWithOAuthPopup(providers, (err, authData) => {
      if (err) {
        console.log('Login Failed!', err)
      } else {
        console.log('Authenticated successfully with payload: ', authData)
        localStorage.setItem('user', JSON.stringify({
          name: base.getAuth()[providers].displayName,
          icon: base.getAuth()[providers].profileImageURL
        }))
        this.onChange(true, this.getUser())
        if (cb) { cb() }
      }
    })
  },
  logout (cb) {
    base.unauth()
    localStorage.clear()
    this.onChange(false, null)
    if (cb) { cb() }
  },
  onChange () {},
  getUser: function () { return JSON.parse(localStorage.getItem('user')) }
}
Run Code Online (Sandbox Code Playgroud)

Login.js

import React, { Component } from 'react'
import auth from './config/auth.js'

export default class Login extends Component {
  constructor (props, context) {
    super(props)
  }

  _login (authType) {
    auth.login(authType, data => {
      this.context.router.replace('/authenticated')
    })
  }
  render () {
    return (
      <div className='login'>
        <button onClick={this._login.bind(this, 'twitter')}>Login with Twitter account</button>
        <button onClick={this._login.bind(this, 'facebook')}>Login with Facebook account</button>
      </div>
    )
  }
}
Login.contextTypes = {
  router: React.PropTypes.object.isRequired
}
Run Code Online (Sandbox Code Playgroud)

win*_*elt 12

如果通过浏览器刷新重新加载页面,组件树和状态将重置为初始状态.

要在浏览器中重新加载页面后恢复以前的状态,您必须这样做

  • 在本地保存状态(localstorage)
  • 和/或在服务器端重新加载.

并且以这样的方式构建页面:在初始化时,检查先前保存的本地状态和/或服务器状态,如果找到,则恢复先前的状态.

  • @G先生是的,安全(和隐私)是您需要考虑的事情.如果使用Firebase,则浏览器刷新将使用Firebase再次检查登录状态,因此Firebase将处理该部分安全性.通常,组件UI状态,例如哪个页面是打开的,哪些下拉列表是打开的,过滤器,复选框,表单中的字段内容(非用户名/密码)等通常不太敏感并且可以在本地存储.就个人而言,我只在本地存储不在用户登录后面的状态.并且仅为经过身份验证的用户存储在服务器(更安全)状态. (2认同)