首页 > 解决方案 > 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>
    )
};

标签: javascripthtmlreactjsdesign-patternsfrontend

解决方案


您可以通过在获取令牌之前添加组件状态来实现一个微调器,指示客户端正在获得授权。

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

推荐阅读