【问题标题】:Using useContext showing an error: Undefined is not an object使用 useContext 显示错误:未定义不是对象
【发布时间】:2021-02-08 22:28:49
【问题描述】:

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

我的 SignInScreen 代码:

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/>;
}

我只是想知道它是否缺少一些组件,我该如何修复它?而且我已经尝试重新安装我的软件包。

【问题讨论】:

  • 您是否在某处为您的上下文添加了提供程序?
  • 以上是我的全部代码,我刚开始学习React-Native,其实不知道provider是什么

标签: javascript android ios react-native expo


【解决方案1】:

您需要在某处为上下文提供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 中登录功能通常不是这样工作的。

【讨论】:

    猜你喜欢
    • 2021-03-17
    • 2022-08-24
    • 2021-12-14
    • 2021-06-25
    • 2015-09-07
    • 2018-07-22
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多