显示具有反应导航的用户令牌

问题描述 投票:0回答:1

我是本机新手,想了解如何显示身份验证后通常保存的React导航用户令牌。

让我们在Slack上使用此exemple更具体。

在此示例中,我想在HomeScreen()函数中显示令牌(虚拟身份验证令牌)。它将使我了解身份验证后如何重用它。

您能否在答复中提供HomeScreen()函数?

感谢您的帮助

react-native authentication react-navigation
1个回答
0
投票

我认为您也可以将state公开到authContext中并在HomeScreen组件中进行访问:

const authContext = React.useMemo(
    () => ({
      authState: state,

      signIn: async data => {
        // In a production app, we need to send some data (usually username, password) to server and get a token
        // We will also need to handle errors if sign in failed
        // After getting token, we need to persist the token using `AsyncStorage`
        // In the example, we'll use a dummy token

        dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
      },
      signOut: () => dispatch({ type: 'SIGN_OUT' }),
      signUp: async data => {
        // In a production app, we need to send user data to server and get a token
        // We will also need to handle errors if sign up failed
        // After getting token, we need to persist the token using `AsyncStorage`
        // In the example, we'll use a dummy token

        dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
      },
    }),
    [state]
  );

请注意,我们将state作为依赖项传递给useMemo挂钩。

并且在您的HomeScreen中,使用类似以下代码:

function HomeScreen() {
  const { signOut, authState } = React.useContext(AuthContext);

  return (
    <View>
      <Text>Signed in!</Text>
      <Text> Token is: {authState.userToken} </Text>
      <Button title="Sign out" onPress={signOut} />
    </View>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.