我已经完成了从aws cognito获取用户的权限,即使在本机应用程序关闭时,如何正确地保持用户登录
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>
);
}
}
答案 0 :(得分:0)
使用AsyncStorage ---------
state = {
isAuthenticated: false
}
componentWillMount(){
const value = await AsyncStorage.getItem('@Mylogin:key');
if (value !== null){
this.setState({
isAuthenticated: true
})
}
}
authenticate(isAuthenticated) {
this.setState({ isAuthenticated });
AsyncStorage.setItem('@Mylogin:key', 'Loggedin');
}
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>
);
}
}
答案 1 :(得分:0)
如果您使用的是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 />
}
}
}