首页 > 解决方案 > 如何使用 aws amplify 保持用户登录 react-native

问题描述

我已经完成了从 aws cognito 获取用户的操作,即使关闭了 react 本机应用程序,我如何才能正确地保持用户登录状态

  state = {
    isAuthenticated: false
  }

  authenticate(isAuthenticated) {
    this.setState({ isAuthenticated })
  }
  render() {
    if (this.state.isAuthenticated) {
      console.log('Auth: ', Auth)
      return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <Text>Hello {Auth.user.username}!</Text>
        </View>
      )
    }
    return (
      <View style={styles.container}>
        <Tabs
          screenProps={{
            authenticate: this.authenticate.bind(this)
          }}
        />
      </View>
    );
  }
}

标签: amazon-web-servicesreact-nativereact-native-androidamazon-cognito

解决方案


如果您使用 Amplify 提供的 Auth API,一旦您使用 Auth.signIn,该 API 将管理您的会话状态。

在您的主要入口组件(可能是 App.js)中,检查 componentDidMount() 方法在您使用有效用户登录之前和之后 Auth.currentAuthenticatedUser() 将返回什么。

... // standard imports
import Amplify, { Auth } from 'aws-amplify';
import awsmobile from './aws-exports';
Amplify.configure(awsmobile);

class App extends Component {
   state = { isLoggedIn: false }
   ...
   async componentDidMount() {
     try {
       const authedUser = await Auth.currentAuthenticatedUser();
       console.log(authedUser) // this means that you've logged in before with valid user/pass. 
       this.setState({ isLoggedIn: true })
     } catch(err) {
       console.log(err) // this means there is no currently authenticated user
     }
   }

   render() {
     if(this.state.isLoggedIn) {
       return <Homescreen /> // or whatever your entry component is
     }
     else {
       return <Login />
     }
   }
}

推荐阅读