反应上下文未定义

时间:2020-05-29 14:56:32

标签: react-native react-navigation react-context

我创建了一个基本的身份验证表单,当我将App.js文件中的所有代码都包含在内时,该表单便可以使用。 但是,当我尝试将页面重构为单独的文件时,上下文抛出一个例外,即它为空。

App.js


import 'react-native-gesture-handler';

import * as React from 'react';
import { Button, Text, TextInput, View, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import AuthContext from './src/utils/AuthContext';
import HomeScreen from './src/components/HomeScreen';
import SignInScreen from './src/components/SignInScreen';
import SplashScreen from './src/components/SplashScreen';

const Stack = createStackNavigator();

export default function App() {
  const [state, dispatch] = React.useReducer(
    (prevState, action) => {
      switch (action.type) {
        case 'RESTORE_TOKEN':
          return {
            ...prevState,
            userToken: action.token,
            isLoading: false,
          };
        case 'SIGN_IN':
          return {
            ...prevState,
            isSignout: false,
            userToken: action.token,
          };
        case 'SIGN_OUT':
          return {
            ...prevState,
            isSignout: true,
            userToken: null,
          };
      }
    },
    {
      isLoading: true,
      isSignout: false,
      userToken: null,
    }
  );

  React.useEffect(() => {
    // Fetch the token from storage then navigate to our appropriate place
    const bootstrapAsync = async () => {
      let userToken;

      try {
        userToken = await AsyncStorage.getItem('userToken');
      } catch (e) {
        // Restoring token failed
        console.log("Restoring token failed" + e);
      }
        dispatch({ type: 'RESTORE_TOKEN', token: userToken });
    };
    bootstrapAsync();
  }, []);

  const authContext = React.useMemo(
    () => ({
      signIn: async data => {
        dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
      },
      signUp: async data => {
        dispatch({ type: 'TO_SIGNUP_PAGE' });
       },
      signOut: () => 
        dispatch({ type: 'SIGN_OUT' }),
    }),
    []
  );

  return (
    <AuthContext.Provider value={authContext}>
      <NavigationContainer>
        <Stack.Navigator>
          {state.isLoading ? (
            // We haven't finished checking for the token yet
            <Stack.Screen name="Splash" component={SplashScreen} />
          ) : state.userToken == null ? (
            // No token found, user isn't signed in
            <Stack.Screen name="SignIn" component={SignInScreen} options={{ title: 'Sign in', animationTypeForReplace: state.isSignout ? 'pop' : 'push',}} />
            ) : (
                // User is signed in
                <Stack.Screen name="Home" component={HomeScreen} />
              )}
        </Stack.Navigator>
      </NavigationContainer>
    </AuthContext.Provider>
  );
}

AuthContext.js


import { createContext } from 'react';

const AuthContext = createContext();

export default AuthContext;

HomeScreen.js


import React, { useContext } from 'react';
import { View, Text, TextInput, Button } from 'react-native';

import AuthContext from '../utils/AuthContext';

const HomeScreen = () => {
    const { signOut } = useContext(AuthContext);

    return (
      <AuthContext>
        <Text>Signed in!</Text>
        <Button title="Sign out" onPress={signOut} />
      </AuthContext>
    );
  }

export default HomeScreen;

错误:


enter image description here

我花了很多时间在此上,并浏览了无数的教程,在我的一生中,我无法弄清我所缺少的...

1 个答案:

答案 0 :(得分:0)

您没有导出上下文。您的App.js文件导出了App组件,但是您正在尝试从该文件访问AuthContext。

最好的方法是将上下文放置在单独的文件中,并将其导入到App.js和HomeScreen.js中

您的上下文文件应如下所示

class MessagesController < ApplicationController
  before_action :authenticate_user!

  def new
    # your code here
  end

end

您可以导入如下所示的其他文件

import { createContext } from 'react';

const AppContext = createContext();

export default AppContext;