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

Swi*_*ngG 1 javascript authentication react-native

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

问题是我在 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);

        }
    });

}
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Srd*_*sic 6

我看到您正在使用反应导航。我已经做了你想要完成的同样的事情,但方式不同。

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

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

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

constructor(props) {
    super(props);

    this.authenticateSession();
}

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

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

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