问题
In my React Native
app, I'm using React Navigation 5
and trying to route users to authentication stack if the user is not authenticated i.e. there's no access_token
in AsyncStorage
.
What I'm confused about is how to get the token from AsyncStorage
because it's an asynchronous process. I can't seem to await
the call in my App
component i.e. it gives me an error if I try and if I don't await
it, then I get a promise
.
How do I implement this using React Navigation 5
?
Here's my App
component:
const App = () => {
const authenticatedUser = AsyncStorage.getItem("access_token");
return (
<Provider store={store}>
<NavigationContainer>
{
authenticatedUser !== null || typeof authenticatedUser !== "undefined"
? <RootNavigator />
: <AuthNavigator />
}
</NavigationContainer>
</Provider>
);
};
export default App;
回答1:
You have to wait for getting a token from AsyncStorage like this.
const App = () => {
const [loading, setLoading] = usState(true)
const [authenticated, setAuthenticated] = usState(false)
useEffect(()=>{async()=>{
const authenticatedUser = await AsyncStorage.getItem("access_token");
setLoading(false)
if(authenticatedUser !== null) setAuthenticated(true)
}},[])
const authenticatedUser = AsyncStorage.getItem("access_token");
return (
<Provider store={store}>
<NavigationContainer>
{ loading &&
<ActivityIndictor size='small' />
}
{
authenticated && !loading
? <RootNavigator />
: <AuthNavigator />
}
</NavigationContainer>
</Provider>
);
};
export default App;
回答2:
I suggest you to use some loader. Load data from your AsyncStorage check if the token was valid and refresh if it is not, load user profile and do more your initialization staff. In code you would do this!
let Loader=()=>{
const [loadingData, setLoading]= useState(null);
let effect=async ()=>{
let credentials = await AsyncStorage.getItem(“data”)
setLoading(credentials||{})
}
useEffect(()=>effect())
If (loadingData===null)
return <LoadingView/>
return <YourRouter {...{loadingData}}/>
来源:https://stackoverflow.com/questions/61665360/react-navigation-5-auth-flow