问题描述
我想设置身份验证流程,但我没有从 SecureStore 获取数据
I want to setup auth flow but i'm not getting the data from SecureStore
Navigator.js
const AppSwitchNavigator = createSwitchNavigator(
{
SignedOut,
SignedIn
},
{
initialRouteName: AsyncStorage.getItem('isSignedIn') == 'true' ? 'SignedIn' : 'SignedOut'
}
)
export default createAppContainer(AppSwitchNavigator)
Login.js
verifyOtp = async code => {
const { phone } = this.state
var response = await Axios.post(
`https://api.msg91.com/api/v5/otp/verify?mobile=91${phone}&otp=${code}&authkey=273478A4j3qbKgj5cbda6ba`
)
if (response.data.type == 'error') {
this.setState({
errMsg: response.data.message
})
} else {
await SecureStore.setItemAsync('isSignedIn', 'true')
this.props.navigation.navigate('Home')
}
}
来自 console.log(SecureStore.getItemAsync('isSignedIn')) 的响应;
undefined
true
true
undefined
true
true
undefined
true
true
现在,由于 initialRouteName
没有获得 isSignedIn
的值,因此它始终保留在 SignedOut
页面上,即登录页面.
Now since initialRouteName
is not getting the value of isSignedIn
it always remains on SignedOut
Page i.e. Login Page.
推荐答案
这是一个几乎每个人都会遇到的经典案例,所以根据 react navigation 的文档 rn-docs,他们总是说最好有 3 个页面,并将初始页面加载为启动屏幕,并在 componentDidMount 方法中启动屏幕执行 asyncstorage 的操作并进行相应的导航.
This is a classic case which almost everyone faces, so as per the docs of react navigation rn-docs, they always say the best thing is to have 3 pages , and load the initial page as splash screen, and inside the componentDidMount method of splash screen do the asyncstorage thing and navigate accordingly.
喜欢这样做:
export default createAppContainer(
createSwitchNavigator(
{
AuthLoading: AuthLoadingScreen,
App: AppStack,
Auth: AuthStack,
},
{
initialRouteName: 'AuthLoading',
}
)
);
并在 AUthLoading
class AuthLoadingScreen extends React.Component {
componentDidMount() {
this._bootstrapAsync();
}
// Fetch the token from storage then navigate to our appropriate place
_bootstrapAsync = async () => {
const userToken = await AsyncStorage.getItem('userToken');
// This will switch to the App screen or Auth screen and this loading
// screen will be unmounted and thrown away.
this.props.navigation.navigate(userToken ? 'App' : 'Auth');
};
// Render any loading content that you like here
render() {
return (
<View>
<ActivityIndicator />
<StatusBar barStyle="default" />
</View>
);
}
}
希望清楚
这篇关于如何在 createSwitchNavigator 中设置动态 initialRouteName?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!