React Native: как сделать контекст доступным из приложения для экрана при использовании реагирующей навигации? - PullRequest
0 голосов
/ 06 марта 2020

Я новичок в 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, который является внуком компонента приложения (в котором я установит токен):

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 не определен

1 Ответ

0 голосов
/ 06 марта 2020

Создайте переменную контекста вне 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>
  )
}  
...