React componentDidMount导致条件视图上的初始闪烁



我正在react应用程序上实现持久登录设计。

我的应用程序将在localStorage中存储上次登录的令牌。在应用程序启动时,我需要解码/验证此令牌并保持他们的登录。如果用户已登录,则会看到主页,否则会看到登录页。问题是,我的应用程序最初会从"未登录"状态闪烁到"已登录"状态,这意味着该应用程序最初在登录页中停留几毫秒,然后在主页中。这种闪烁有点刺耳,当然不是一个好的ux。

我应该有一个初始加载屏幕,还是有更好的方法来处理这个条件视图场景。

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>
)
};

最新更新