我正在开发React WebSite的登录系统 . 我们使用api_tokens来访问API并检索信息作为验证用户凭据 . 当auth失败并重定向到用户登录页面时,我需要重新调整所有内容,目前我使用redux作为app全局状态 . 问题是我在浏览器localStorage中保存api_token,当浏览器清除历史记录或其他东西修改api_token时,我需要调度UNAUTH_USER ........
我想知道我是否可以附加一些eventListener ......如果是正确的解决方案..
代码如下所示:
import React from 'react'
import Header from './Header'
import Navigation from '../navigation/components/Navigation'
import Ribbon from '../ribbon/Ribbon'
import Footer from './Footer'
import Shortcut from '../navigation/components/Shortcut'
import LayoutSwitcher from '../layout/components/LayoutSwitcher'
import {connect} from 'react-redux'
// require('../../smartadmin/components/less/components.less');
class Layout extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
if(!this.props.authenticated) {
this.props.router.push('/login');
}
}
componentWillUpdate(nextProps) {
if(!nextProps.authenticated) {
this.props.router.push('/login');
}
}
render() {
if (!this.props.authenticated) {
this.props.router.push('/login');
return null;
}
else {
return (
<div>
<Header />
<Navigation />
<div id="main" role="main">
<LayoutSwitcher />
<Ribbon />
{this.props.children}
</div>
<Footer />
<Shortcut />
</div>
)
}
}
}
const mapStateToProps = (state) => {
return {
authenticated: state.auth.authenticated
};
}
export default connect(mapStateToProps)(Layout);
1 回答
我在我的应用程序中做同样的事情 . 对于我的Sagas所做的每次调用,如果发生api错误并且引发了403 expired / unvalid令牌,我会在那里发送一个redux动作来清除localstorage并断开用户连接(我之前有一个刷新令牌机制重试) .
我不确定您是否可以将eventListener附加到localStorage到期,但是检查您的API调用机制将是IMO的一个好习惯 .
最好