使用我的应用程序组件包装时,Context.provider抛出错误

时间:2020-09-17 14:38:02

标签: javascript reactjs react-context

我的应用程序运行良好,直到我添加以下代码行并将应用程序组件包装在一起:

错误:元素类型无效:预期为字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。您可能忘记了从定义文件中导出组件,或者您可能混淆了默认导入和命名导入。

这是我的应用

import React, { useState, useCallback } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

import Users from "./pages/Users";
import MainNavigation from "./common/Navigation/MainNavigation";
import UserPlaces from "./pages/places/UserPlaces";
import NewPlace from "./pages/places/NewPlace";
import UpdatePlace from "./pages/places/UpdatePlace";
import Auth from "./pages/Users/Auth";
import { AuthContext } from "./context/auth-context";

const App = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  const login = useCallback(() => {
    setIsLoggedIn(true);
  }, []);

  const logout = useCallback(() => {
    setIsLoggedIn(false);
  }, []);

  return (
    <AuthContext.provider
      value={{ isLoggedIn: isLoggedIn, login: login, logout: logout }}
    >
      <Router>
        <MainNavigation />
        <main>
          <Switch>
            <Route path="/" component={Users} exact />
            <Route path="/:userId/places" component={UserPlaces} exact />
            <Route path="/places/new" component={NewPlace} exact />
            <Route path="/places/:pId" component={UpdatePlace} exact />
            <Route path="/auth" component={Auth} exact />
          </Switch>
        </main>
      </Router>
    </AuthContext.provider>
  );
};

export default App;

这是认证上下文文件

import { createContext } from "react";

export const AuthContext = createContext({
  isLoggedIn: false,
  login: () => {},
  logout: () => {},
});

不知道上下文有什么问题

1 个答案:

答案 0 :(得分:0)

尝试改用AuthContext.Provider

// Not AuthContext.provider
<AuthContext.Provider value={...}>
      ...
</AuthContext.Provider>