感谢您阅读我的第一个问题。
我尝试使用共享根进行身份验证,使用 react、react-router 和 firebase。所以,我想保留App.js
的用户状态。但是当我尝试刷新浏览器时,没有找到用户状态。
我试图保存到本地存储。但是有没有办法在浏览器刷新后保持组件状态而没有localStorage
?
应用程序.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
}
身份验证.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')) }
}
登录.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
}