javascript - 检查用户是否在 native react 之前登录

标签 javascript authentication react-native

在我的 react native 应用程序中,我将用户信息安全地保存在 key 链上,以便在他们登录一次后,我保存信息,然后下次用户来时,信息已经存在,因此用户不需要登录。

问题是我在 componentDidMount 中进行检查,然后如果用户以前从未登录过或在上次访问中注销过,我会将他们重定向到登录屏幕,如下所示:

componentDidMount() {
    //Need to check if they've signed in before by checking the USER_INFO.
    SecureStore.getItemAsync("USER_INFO").then(response => {
        //Have they signed in before?
        if (response !== undefined) {
          //yes.
          //continue with app stuff.
        }
        else {
          //Not logged in before need to go to login.
          const resetAction = NavigationActions.reset({
            index: 0,
            actions: [
              NavigationActions.navigate({ routeName: 'Login', params: this.props.navigation.state.params }),
            ]
          });
          this.props.navigation.dispatch(resetAction);

        }
    });

}

问题是我收到一条警告“警告:只能更新已安装或正在安装的组件”。这通常意味着您在未安装的组件上调用了 setState、replaceState 或forceUpdate。这是一个禁止操作。这是有道理的,因为我在屏幕渲染之前进行重定向,但问题是,我应该在哪里执行这些检查?

谢谢

最佳答案

我发现您正在使用 react 导航。我已经做了你想要完成的同样的事情,但是以不同的方式。

为了简化,我在导航器中有三个屏幕

// Navigator.js
export const RootNavigator = StackNavigator({
  Splash: { screen: SplashView },
  Login: { screen: LoginView },
  RootDrawer: { screen: RootDrawer }
}, {
  headerMode: 'none',
  initialRouteName: 'Splash'
});

然后在我的 SplashView(这是我的起点)中,我在其构造函数中对用户进行身份验证。在验证用户身份时,SplashView 只是渲染一个文本,上面写着“Splash Screen”,但显然可以是任何内容。

constructor(props) {
    super(props);

    this.authenticateSession();
}

authenticateSession() {
    const { navigation } = this.props;
    dispatch(storeGetAccount())
      .then(() => {
        navigation.dispatch(navigateToAccountView(true));
      })
      .catch(() => {
        navigation.dispatch(navigateToLoginView());
      });
}

函数navigateToAccountView() 和navigateToLoginView()只是为了让我可以在其他地方使用它们,但navigateToLoginView()看起来像这个

export function navigateToLoginView() {
  return NavigationActions.reset({
    index: 0,
    key: null,
    actions: [
      NavigationActions.navigate({ routeName: 'Login' })
    ]
  });
}

关于javascript - 检查用户是否在 native react 之前登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49019431/

相关文章:

javascript - PHP/JS登录系统

reactjs - 无法在 React tanstack 查询中传递参数

JavaScript FileReader 海量结果

javascript - 如何在 jqGrid 的请求中将 postData._search 设置为 true?

javascript - Promise在这种情况下如何实现?

java - 用户登录时启用页面上的按钮/GWT

azure - 如何使用我的 AAD 凭据登录到我的 Azure VM?

react-native - 在 React Native 中卸载应用程序时,我可以捕获事件吗?

react-native - React Native - Derectional Pad 支持 Android TV App

javascript - vendor 前缀 CSS 解决方法的速度和大小(Bootstrap)