我是本机新手,想了解如何显示身份验证后通常保存的React导航用户令牌。
让我们在Slack上使用此exemple更具体。
在此示例中,我想在HomeScreen()函数中显示令牌(虚拟身份验证令牌)。它将使我了解身份验证后如何重用它。
您能否在答复中提供HomeScreen()函数?
感谢您的帮助
我认为您也可以将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>
);
}