我正试图从react-router -repo实现auth-flow example,但我作为一个ReactJS初学者 .
我的登录状态是基于CSRF-cookie的存在,所以我的应用程序中有一个方法可以检索CSRF-cookie并将其值保存在以下状态:
@autobind
class App extends React.Component {
constructor() {
super();
this.state = {
csrfToken : '',
log : {}
}
}
setCSRFToken() {
this.state = { csrfToken : cookie.load('csrf') };
this.setState({ csrfToken : this.state.csrfToken });
}
loggedIn() {
return !!this.state.csrfToken
}
因为我只想在登录时查看我的组件,所以我尝试根据使用onEnter = 的loggedIn()更改路径中的路径:
function requireAuth(nextState, replace) {
if (!App.loggedIn()) {
console.log('No csrfToken found, asking for login')
replace({
pathname: '/login',
state: {nextPathname: nextState.location.pathname }
})
}
}
render((
<Router history={hashHistory}>
<Route path="/" component={App} onEnter={requireAuth}>
<IndexRoute component={Home}/>
<Route path="/hello" component={Hello}/>
</Route>
</Router>
), document.querySelector('#main'))
App.loggedIn()虽然不起作用,因为它不是公共函数 . 根据这个answer,ReactJS中的公共函数无法访问内部状态,正如React的体系结构所预期的那样,因此使用static实现它无济于事 .
我可以继续将登录状态保存在本地存储中,但我想知道在ReactJS中是否有不同的方法来解决这个问题 .
1 回答
我在Store中设置登录状态(如Flux建议)和路线:
效果很好,用这个构建了几个应用程序:)
UserStore.js: