React Native:如何在使用 React 导航时使上下文从应用程序可用到屏幕?

React Native : how to make context available from App to a Screen when using react navigation?

我是 RN 的新手并尝试制作一个登录系统,我在全局范围内存储电子邮件和密码(为了代码的简洁性而隐藏)以便使用组件进行调用到服务器,简而言之,我试图将电子邮件保持在应用程序级别,并避免从一个屏幕传递到另一个屏幕。

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

App 之外创建上下文变量并使其可导出。

export const AuthenticationContext = React.createContext();

function App() {
  return (
    <AuthenticationContext.Provider value={{email,setEmail}}>
      // Children
    </AuthenticationContext.Provider>

  )
}

那么在HomeScreen上你可以通过以下方式使用

使用 useContext 挂钩:

import { AuthenticationContext } from './App';

function HomeScreen (props) => {
  const { email, setEmail } = React.useContext(AuthenticationContext);
  const onPress = () => {
    props.navigation.navigate('Profile');
  }
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <LoginForm {...props} />
      { props.token != null ? (
          <Button
            title="Go to Profile"
            onPress={onPress} 
          /> 
        ) : null
      }
    </View>
  )
}  

或没有

import { AuthenticationContext } from './App';

function HomeScreen (props) => {
  const onPress = () => {
    props.navigation.navigate('Profile');
  }
  return (
    <AuthenticationContext.Consumer>
      {({ email, setEmail }) => (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <LoginForm {...props} />
          { props.token != null ? (
              <Button
                title="Go to Profile"
                onPress={onPress} 
              /> 
            ) : null
          }
        </View>
      }
    </AuthenticationContext.Consumer>
  )
}