amazon-web-services - 如何使用 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>
);
}
}
解决方案
如果您使用 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 />
}
}
}
推荐阅读
- sqlite - 从日期之间提取数据时如何拉出额外的行?
- protractor - 量角器浏览器实例限制
- reactjs - 调度未定义/存储未在操作中定义
- python - 安装 pip autopep8 失败,语法无效?
- javascript - 我可以使用 Sublime Text 或 Atom.io 等代码编辑器将 CSS、HTML 和 JAVASCRIPT 放在一个文件中吗?谢谢
- node.js - 在外部硬盘驱动器上安装 node.js/npm (Mac OS Mojave)
- c# - 我得到一个 System.IndexOutOfRangeException
- sql - 多对多关系的全文搜索
- node.js - 分类命令类型
- yql - 是否可以通过嵌套属性值或对象数组查询对象过滤?