如果页面受保护且用户未登录,如何重定向到登录? [英] How Redirect to Login if page is protected and the user is not signed in?

查看:64
本文介绍了如果页面受保护且用户未登录,如何重定向到登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一些公共屏幕即使用户未登录也可以访问,并且一些屏幕受到保护(您必须登录才能访问它们).

In my App I have some public screens that are accessible even if the user is not logged in, and some screens are protected (you must be logged in to access them).

我对问题的解决方法是检查组件willFocus Listener,如果没有登录,用户应该被重定向到loginPage.

My solution to the problem is to check the component willFocus Listener and if not logged in, the user should be redirected to the loginPage.

export async function ProtectRoute(navigation){

//if page will enter and the user is not authenticated return to login
navigation.addListener(
    'willFocus',
    async () => {
        let token = await getTokenAsync();

        if(!token){
            navigation.navigate('Login');
        }
    })
}

在我的屏幕中,我在 ComponentWillMount 生命周期中调用了这个函数.问题是验证令牌需要一秒钟,并且页面会短暂显示.

In my screen I Call this function in ComponentWillMount lifecycle. The issue is that it takes like a second to verify the token and the page is displayed briefly.

我怎样才能让他直接进入登录页面而没有延迟?

How can I make it so that he goes directly to the Login Page without that lag ?

推荐答案

问题是验证令牌需要一秒钟,并且页面会短暂显示.

The issue is that it takes like a second to verify the token and the page is displayed briefly.

原因是因为从/向 AsyncStorage 读取/写入是一个异步操作.

The reason is because reading/writing from/to AsyncStorage is an asychronous operation.

在我的屏幕中,我在 ComponentWillMount 生命周期中调用此函数.

In my screen I Call this function in ComponentWillMount lifecycle.

我建议您不要使用 ComponentWillMount 生命周期,因为它已被弃用并且将从 React 中删除 (https://reactjs.org/docs/react-component.html#unsafe_componentwillmount)

I suggest you to not use ComponentWillMount lifecycle because it's deprecated and it will be removed from React (https://reactjs.org/docs/react-component.html#unsafe_componentwillmount)

在介绍之后,现在我向您展示我是如何在我的应用中实现这一目标的:CONTEXT API!(https://reactjs.org/docs/context.html)

After this introduction, now i show you how I have achieved this in my app: CONTEXT API! (https://reactjs.org/docs/context.html)

Context 提供了一种通过组件树传递数据的方法,而无需在每个级别手动向下传递 props.

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

如何实现上下文API:上下文将是您的 App.js 文件的状态".你的根 App.js 将成为上下文的提供者,而其他需要上下文的视图被称为上下文的消费者.

How to implement context api: the context will be the 'state' of your App.js file. You root App.js will be the provider of the context, while other views which will need the context are called the consumers of the context.

  1. 首先,您需要将上下文的骨架"创建到一个单独的文件中,如下所示:

// AuthContext.js
import React from 'react'
const AuthContext = React.createContext({
  isLogged: false,
  login: () => {},
  logout: () => {}
})
export default AuthContext

  1. 您的 App.js 将导入、包含和初始化上下文:

// App.js
// all necessary imports
import AuthContext from '....'
export default class App extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      isAuth: false,
      login: this.login,
      logout: this.logout
    }

    login = async userData => {
    // do your login stuff and then
    this.setState({ isAuth: true })
    }

    logout = async () => {
    // do your logout stuff and then
    this.setState({ isAuth: false })
    }

    async ComponentDidMount () {
      // check the asyncStorage here and then, if logged:
      this.setState({ isAuth: true })
    }

    render () {
      return (
        <AuthContext.Provider value={this.state}>
          <AppContainer />
        </AuthContext.Provider>
      )
    }

  1. 然后,在包含在 AppContainer 中的视图中,您可以像这样访问上下文:

import AuthContext from '.....'
// all necessary imports
export default class YourView extends React.Component<Props, State> {
  constructor (props) {
    super(props)
    this.props = props
    this.state = { ... }
  }

  // THIS IS IMPORTANT
  static contextType = AuthContext
  // with this, you can access the context through 'this.context'

  ComponentDidMount () {
    if (!this.context.isAuth) this.props.navigation.navigate('login')
  }

这种方法的优点:

  1. 检查布尔值的速度非常快,您不会注意到空白屏幕.
  2. 在您的应用中随处共享身份验证上下文
  3. 仅在应用首次安装时访问 asyncstorage,而不是每次需要检查用户是否登录时访问
  4. 在您的应用中随处共享登录/注销方法

这篇关于如果页面受保护且用户未登录,如何重定向到登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆