undefined不是react-native中的对象评估“ context._context”

问题描述

我正在尝试在我的react-native应用程序中实现useContext,但收到错误消息:“未定义不是对象(正在评估'context._context')”。

这是我的代码(尝试使用EmailContext):

import React,{useState} from 'react';

export const Emailcontext = React.createContext("");

const ContextStore = ({children}) => {
    const [emailAddress,setEmailAddress] = useState("");

    return(
        <Emailcontext.Provider value={[emailAddress,setEmailAddress]}>
            {children}
        </Emailcontext.Provider>
    );
}

export default ContextStore;

在这里,我用ContextStore包装我的应用程序:

    <ContextStore>
      <NavigationContainer>
        <Stack.Navigator 
          screenoptions={{headerShown: false}}
        >
          <Stack.Screen name='EmailVerification' component={EmailVerification} />
          <Stack.Screen name='VerifyEmailExplenation' component={VerifyEmailExplenation} />
        </Stack.Navigator>
      </NavigationContainer>
    </ContextStore>

然后在此组件中未定义上下文:

import React,{useContext,useState} from 'react';
import {EmailContext} from '../ContextStore'

const EmailVerification = ({navigation}) => {
    const [emailAddress,setEmailAddress] = useContext(EmailContext);
  
    return(
      **jsx element**
    );
}
export default EmailVerification;

不能为此找到任何解决方案。

解决方法

我误认为您正在导入EmailContext,它应该是Emailcontext 您的电子邮件验证组件应如下所示:

import React,{useContext,useState} from 'react';
import {Emailcontext} from '../ContextStore'

const EmailVerification = ({navigation}) => {
    const [emailAddress,setEmailAddress] = useContext(Emailcontext);
  
    return(
      **jsx element**
    );
}
export default EmailVerification;

您还已将ContextStore设置为默认导出,因此在将其导入到app.js中时,请确保按以下方式进行导入:

import ContextStore from '...correct path'

我知道您使用的是react-native,但这是CRA的代码笔,其中将index.js包装在提供程序中,并正确导入到app.js中以模拟您的EmailVerification组件。

https://codesandbox.io/s/admiring-shaw-5yrs3?file=/src/App.js