How to set dynamic initialRouteName in createSwitchNavigator?

荒凉一梦 提交于 2021-02-10 05:26:39

问题


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')
    }
  }

response from console.log(SecureStore.getItemAsync('isSignedIn'));

undefined
true
true
undefined
true
true
undefined
true
true

Now since initialRouteName is not getting the value of isSignedIn it always remains on SignedOut Page i.e. Login Page.


回答1:


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.

Like do this :

 export default createAppContainer(
      createSwitchNavigator(
        {
          AuthLoading: AuthLoadingScreen,
          App: AppStack,
          Auth: AuthStack,
        },
        {
          initialRouteName: 'AuthLoading',
        }
      )
    );

and in 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>
    );
  }
}

hope its clear



来源:https://stackoverflow.com/questions/59841723/how-to-set-dynamic-initialroutename-in-createswitchnavigator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!