【发布时间】:2020-03-06 14:10:24
【问题描述】:
我是 RN 的新手并尝试创建一个登录系统,我将电子邮件和密码(为了代码简洁而隐藏)存储在全局范围内,以便使用组件调用服务器,简而言之,我试图将电子邮件保持在 App 级别,并避免从一个屏幕传递到另一个屏幕。
function App() {
const [email, setEmail] = React.useState('')
const [token,setToken] = React.useState(null)
const AuthenticationContext = React.createContext();
return (
<AuthenticationContext.Provider value={{email,setEmail}}>
<NavigationContainer>
<Stack.Navigator>
>
{token == null ? (
<Stack.Screen name="Home" component={HomeScreen} />
) : (
<Stack.Screen
name="Profile"
component={ProfileScreen}
options={({ route }) => ({ title: route.params.name })}
/>
)}
</Stack.Navigator>
</NavigationContainer>
</AuthenticationContext.Provider>
);
}
还有 HomeScreen 和 LoginForm 组件,它是 App 组件的孙子(我将在其中设置令牌):
function HomeScreen({ navigation, route },props ) {
return (
<AuthenticationContext.Consumer>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<LoginForm {...props} />
{ props.token != null ?
<Button
title="Go to Profile"
onPress={() => navigation.navigate('Profile')}
/>
: null}
</View>
</AuthenticationContext.Consumer>
);
}
但是我得到消息:AuthenticationContext 没有定义
【问题讨论】:
标签: reactjs react-native react-hooks react-navigation-v5