检查用户是否在响应本机之前登录

问题描述 投票:0回答:2

在我的本机应用程序中,我将用户信息安全地保存在密钥链上,以便在他们登录一次后,我保存信息,然后在用户下次访问时,信息已经存在,因此用户不会需要登录。

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

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。这是一个无操作。'。这是有道理的,因为我在屏幕渲染之前重定向,但问题是,我应该在哪里执行这些检查?

谢谢

javascript authentication react-native
2个回答
4
投票

我看到你正在使用react-navigation。我做了同样的事情,你试图以不同的方式完成。

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

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

然后在我的SplashView(这是我的起点)中,我在其构造函数中验证用户。虽然它正在验证用户,但SplashView只是渲染一个显示“启动画面”的文本,但显然可以是任何东西。

constructor(props) {
    super(props);

    this.authenticateSession();
}

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

功能navigateToAccountView() and navigateToLoginView()就是这样我可以在其他地方使用它们但是navigateToLoginView()看起来像这样

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

0
投票

通常并且据我所知,处理此类检查的最佳方法是通过一些HOC(High Order Component)包装您的组件在那里执行您的逻辑,并且根据用户是否通过检查,您可以重定向到登录页面或加载用户数据并继续呈现您的组件。

这是一个很好的做法,因此您可以创建一个withAuth() HOC,它将包装只能由经过身份验证的用户访问的组件或应用程序部分。而且你将拥有一个高度可重用的组件。

因此,您将导出“受保护的组件”,如下所示:

export default withAuth(myComponent)

withAuth HOC而不是在你的组件中执行逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.