我正在使用 native-CLI 来构建 react-native 应用程序。一切正常,但是当我通过 API 登录用户时,我收到令牌和其他值。我将它们设置在 AsyncStorage 中,它应该跳转到买家仪表板屏幕,但它不能,但是当我刷新应用程序时,它会转到买家仪表板。我的 login.js 位于 app.js 中的单独文件和导航堆栈中。
Login.js => 我只是粘贴了一个在按下登录按钮时运行的函数
const login = async () => {
if (name != '' && password != '') {
const login_Credentials = new FormData();
login_Credentials.append('username', name);
login_Credentials.append('password', password);
setPress(true)
await axios({
method: 'POST',
url: api + 'login/',
data: login_Credentials,
headers: { 'Content-Type': 'multipart/form-data' }
}).then(async function (response) {
if (response.data.Success == true) {
const token = response.data.token.toString();
const super_user_status = response.data.super_user_status.toString();
const isLoggedIn = "1"
console.log('Logged In and set Storgae')
await AsyncStorage.multiSet([['isLoggedIn',isLoggedIn],['token', token], ['super_user_status', super_user_status]])
setName('')
setPassword('')
setPress(false)
} else if (response.data.Success == false) {
setPress(false)
setErrorMsg(response.data.Error)
setName('')
setPassword('')
}
}).catch(function (response) {
console.log(response, "error");
})
} else {
setErrorMsg('Please Enter Username/Password.')
}
}
和
App.js
// <AuthStackScreen />
// <BuyerDashboardStackScreens />
const App = () => {
const [user, setUser] = useState(false)
const [role, setRole] = useState('seller')
useEffect(()=>{
getKeysData(dataKeys)
},[])
const dataKeys = ['token', 'super_user_status', 'isLoggedIn'];
const getKeysData = async (keys) => {
const stores = await AsyncStorage.multiGet(keys);
const aData = stores.map(([key, value]) => ({ [key]: value }))
const token = aData[0]['token']
const super_user_status = aData[1]['super_user_status']
const isLoggedIn = aData[2]['isLoggedIn']
console.log('token',token)
console.log('SuperUser', super_user_status)
console.log('Log',isLoggedIn)
if(isLoggedIn == '1'){
setUser(true)
}else{
setUser(false)
}
}
//AsyncStorage.clear()
return (
<NavigationContainer>
{ user == false ?
<AuthStackScreen />
:
<BuyerDashboardStackScreens />
}
</NavigationContainer>
);
};
在 app.js 中,我创建了两个堆栈,一个是 auth,另一个是买家。正如您在上面的代码中看到的,我创建了 const [user, setUser] = useState(false)
,当我在 AsyncStorage 中获取值时,它应该更新 hook true 的值并根据返回函数中的条件运算符更改堆栈。
但它会在单击登录按钮后刷新应用程序时将页面从登录更改为仪表板。
我缺少什么来实现我的功能?
感谢您的建议。