Я думаю, вы можете также выставить 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
hook .
А в вашем 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>
);
}