Reactjs React Native with asynchstorage中的身份验证
在我的项目中,当uid保存在异步存储中时,表示用户已经登录Reactjs React Native with asynchstorage中的身份验证,reactjs,react-native,jwt,Reactjs,React Native,Jwt,在我的项目中,当uid保存在异步存储中时,表示用户已经登录 当前代码 Index.js 从“React”导入React; 从“app/src/common/Auth”导入Auth; 从“react native”导入{Text}; 导出默认类索引扩展React.Component{ 建造师(道具){ 超级(道具); 此.state={ 作者:是的, }; } 异步组件didmount(){ wait this.setState({auth:wait auth.user()}); } rende
当前代码 Index.js
从“React”导入React;
从“app/src/common/Auth”导入Auth;
从“react native”导入{Text};
导出默认类索引扩展React.Component{
建造师(道具){
超级(道具);
此.state={
作者:是的,
};
}
异步组件didmount(){
wait this.setState({auth:wait auth.user()});
}
render(){
const{auth}=this.state;
返回(
{!啊(
你需要登录!
) : (
您已登录!
)}
)
}
}
Auth.js
从'react native'导入{AsyncStorage};
导出默认值{
异步用户(){
让结果=真;
const response=wait AsyncStorage.getItem('uid');
如果(!响应){
结果=假;
}
返回结果;
},
};
这段代码正在工作,但我想让它更简单,就像一个函数一样
如果您能给我一些建议,我将不胜感激。您打算在多个地点使用它吗?为什么不在您的组件中这样做呢
async componentDidMount() {
const auth = await AsyncStorage.getItem('uid');
this.setState({ auth });
}
您可以使用promise并在Index.js中完成所有工作,如
AsyncStorage.getItem('uid').then((uid) => {
this.setState({
auth : (uid) ? true : false
})
})
或者干脆用
const uid = await AsyncStorage.getItem('uid');
this.setState({ auth : (uid) ? true : false });
是的,我将在不止一个地点使用它。您是否使用过像redux这样的全局状态管理?因为你可以在这里取一次,然后在你需要的任何其他组件中从redux获取值,我不使用redux。谢谢,看起来有比我现在的更好的方法。