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
如果通过浏览器刷新重新加载页面,组件树和状态将重置为初始状态.
要在浏览器中重新加载页面后恢复以前的状态,您必须这样做
并且以这样的方式构建页面:在初始化时,检查先前保存的本地状态和/或服务器状态,如果找到,则恢复先前的状态.
| 归档时间: |
|
| 查看次数: |
13523 次 |
| 最近记录: |