[英]how to update the state of app.js using other component in react native?
我正在使用本機 CLI 構建 react-native 應用程序。 一切正常,但是當我通過 API 登錄用戶時,我收到了令牌和其他值。 我將它們設置在 AsyncStorage 中,它應該跳轉到買家儀表板屏幕,但它不能,但是當我刷新應用程序時,它會轉到買家儀表板。 基本上,按下登錄按鈕后它不會刷新 app.js,它也應該刷新 app.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.')
}
}
應用程序.js
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>
);
};
我使用 AsyncStorage 更新 app.js 中的 state。
如您所知, AsyncStorage
是異步的,用戶在開始時為 false,並且 state 未加載到 state。 你應該設置一個加載 state 並且直到 state 沒有從AsyncStorage
加載你顯示一個啟動屏幕。 登錄時,從響應中設置用戶 state。
const [user, setUser] = useState(false)
const [role, setRole] = useState('seller')
const [isLoading, setIsLoading] = useState(true)
...
const getKeysData =() => {
// wait for storage data
// setUser
setIsLoading(false)
}
...
if(isLoading) return <Loader />
return <Navigation.../>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.