TypeError: Cannot read property 'Provider' of undefined React Native Context

TypeError: Cannot read property 'Provider' of undefined React Native Context

我在 App.js 中遇到错误 TypeError: Cannot read property 'Provider' of undefined。在行 <AuthContext.Provider value={{ authorized, setAuthorized }}>.

App.js
....
import React, { useState } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import MyDrawer from './components/Drawer';
import AuthStack from './components/AuthStack';
import AuthContext from './components/authContext.js';

export default function App() {
  const [authorized, setAuthorized] = useState(false)

  return authorized ? (
    <NavigationContainer>
      <MyDrawer />
    </NavigationContainer>
  ) : (
    <AuthContext.Provider value={{ authorized, setAuthorized }}>
      <NavigationContainer>
        <AuthStack />
      </NavigationContainer>
    </AuthContext.Provider>
  );
}

这是我的上下文:

authContext.js
....
import React from "react";

export const AuthContext = React.createContext({
    authorized: false,
    setAuthorized: () => {},
});

问题有什么想法吗?

看来您只需要使用 {} 导入:

import { AuthContext } from './components/authContext.js';

因为您没有导出默认的 AuthContext。更多信息 here