【问题标题】:React componentDidMount causing initial flickering on conditional viewsReact componentDidMount 导致条件视图上的初始闪烁
【发布时间】:2020-02-22 19:49:27
【问题描述】:

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

我的应用程序将在 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>
    )
};

【问题讨论】:

  • 您可以添加第三个条件来检查您在尝试验证用户身份之前设置的加载状态。

标签: javascript html reactjs design-patterns frontend


【解决方案1】:

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

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

【讨论】:

  • 谢谢,这是有道理的。我不确定这是否是正确的设计模式,因为我的“加载”需要很短的时间。但我可以看到自己在未来添加更多的东西来预加载,所以这似乎是一个很好的解决方案
猜你喜欢
  • 2020-09-19
  • 1970-01-01
  • 2020-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多