javascript - React componentDidMount 导致条件视图上的初始闪烁
问题描述
我正在我的反应应用程序上实现持久登录设计。
我的应用程序将在 localStorage 中存储上次登录的令牌。在应用程序启动时,我需要解码/验证这个令牌并保持他们的登录。如果用户已登录,则他们会看到主页,否则他们会看到登录页面。问题是我的应用程序最初会从“未登录”状态闪烁到“登录状态”,这意味着该应用程序最初在登录页面中停留几毫秒,然后在主页中。这种闪烁有点刺耳,当然不是一个好的用户体验。
我应该有一个初始加载屏幕还是有更好的方法来处理这个条件视图场景。
constructor(props){
super(props);
this.state = {
isAuthenticated: false,
username: null
};
this.dispatch = this.dispatch.bind(this);
};
componentDidMount(){
const token = localStorage.token;
if (token){
axios.get('api/users/getUser', {headers: {
"Authorization": token
}})
.then(res => {
this.dispatch(this.state, {
type: 'LOGIN', payload: res.data
})
})
}
}
render(){
return (
<AuthContext.Provider
value = {{
'state': this.state,
'dispatch': this.dispatch
}}
>
<div className='App'>
{!this.state.isAuthenticated ? <LandingPage /> : <Home />}
</div>
</AuthContext.Provider>
)
};
解决方案
您可以通过在获取令牌之前添加组件状态来实现一个微调器,指示客户端正在获得授权。
constructor(props){
super(props);
this.state = {
isAuthenticated: false,
isAuthenticating: false,
username: null,
};
this.dispatch = this.dispatch.bind(this);
};
componentDidMount(){
const token = localStorage.token;
if (token){
this.setState({ isAuthenticating: true })
axios.get('api/users/getUser', {headers: {
"Authorization": token
}})
.then(res => {
this.dispatch(this.state, {
type: 'LOGIN', payload: res.data
})
this.setState({ isAuthenticating: false })
})
}
}
render(){
return (
<AuthContext.Provider
value = {{
'state': this.state,
'dispatch': this.dispatch
}}
>
<div className='App'>
{this.state.isAuthenticating ? <Spinner /> : null }
{!this.state.isAuthenticated ? <LandingPage /> : <Home />}
</div>
</AuthContext.Provider>
)
};
推荐阅读
- ios - 条件绑定的初始化器
- sql - 计算经过时间 (DATEDIFF),同时减去休息和午餐时间
- python - 从测试模块导入
- go - Go - VSCode - 模块非常慢
- ejs - 是否可以在 ejs 中制作自定义 html 头标签?
- python - scipy.interpolate.make_interp_spline 如何检索所有系数?
- hibernate - Hibernate:Schema-validation:即使在hibernate刚刚生成表之后也缺少表
- vue.js - 返回与原始条目相同的条目后的 Faunadb
- sql - 一对多关系:在多侧按列分组并计算一侧的行数
- python-3.x - 保持 QPlainTextEdit 尽可能小而不需要滚动条