使用 useContext 显示错误:未定义不是对象

时间:2021-02-08 22:28:49

标签: javascript android ios react-native expo

我正在尝试在 React-Native 中编写登录屏幕,但出现以下错误: enter image description here

我的登录屏幕代码:

import React from 'react';

import { 
    View, 
    Text, 
    TouchableOpacity, 
    TextInput,
    Platform,
    StyleSheet ,
    StatusBar,
    Alert
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import LinearGradient from 'react-native-linear-gradient';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import Feather from 'react-native-vector-icons/Feather';

import { useTheme } from 'react-native-paper';

import { AuthContext } from '../components/context';

import Users from '../model/users';

const SignInScreen = ({navigation}) => {

    const [data, setData] = React.useState({
        username: '',
        password: '',
        check_textInputChange: false,
        secureTextEntry: true,
        isValidUser: true,
        isValidPassword: true,
    });

    const { colors } = useTheme();

    const { signIn } = React.useContext(AuthContext);

    const textInputChange = (val) => {
        if( val.trim().length >= 4 ) {
            setData({
                ...data,
                username: val,
                check_textInputChange: true,
                isValidUser: true
            });
        } else {
            setData({
                ...data,
                username: val,
                check_textInputChange: false,
                isValidUser: false
            });
        }
    }

我的 context.js:

import React from 'react';

export const AuthContext = React.createContext();

我的 app.js:

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import SignInScreen from "./screens/SignInScreen";


export default function App() {
  return <SignInScreen/>;
}

我只是想知道它是否缺少某些组件以及如何修复它?我已经尝试重新安装我的软件包。

1 个答案:

答案 0 :(得分:0)

您需要在某处为上下文提供 signIn 函数。通常,这是通过上下文提供程序实现的。您可以在 docs 中找到更多信息。它可能看起来像这样:

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import SignInScreen from "./screens/SignInScreen";

export const AuthContext = React.createContext();
const signIn = () => {
  // ... sign into an account or something
}

export default function App() {
  return (
    <AuthContext.Provider value={{signIn}}>
        <SignInScreen/>
    </AuthContext.Provider>
  )
}

然而,阅读文档并考虑为什么在这里使用上下文可能是值得的,因为这通常不是 React/React-Native 中登录功能的工作方式。