reactjs 无法从上下文中解构对象的属性

5fjcxozz  于 2023-03-29  发布在  React
关注(0)|答案(7)|浏览(164)

由于一个新问题,我重新发布了一个与我上一个类似的问题。我试图在我的react应用程序中使用带有钩子的上下文来管理身份验证。我得到了错误TypeError: Cannot destructure property 'isAuthenticated' of 'Object(...)(...)' as it is undefined.,但是当我console.log它定义的属性时,我看到的是false而不是undefined
我在authContext.js中有上下文定义和提供程序

import React, { useState, useEffect, createContext } from "react";
import axios from "axios";

const AuthContext = createContext();
export { AuthContext };

const AuthContextProvider = (props) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  const setAuth = (boolean) => {
    setIsAuthenticated(boolean);
  };

  const apiOptions = {
    url: "users/is-verified",
    method: "GET",
    headers: {
      token: localStorage.token,
    },
  };

  function isAuth() {
    axios(apiOptions)
      .then((response) => {
        console.log("auth ran");
        const resData = response.data;
        resData === true ? setIsAuthenticated(true) : setIsAuthenticated(false);
      })
      .catch((error) => {
        console.log(error.response);
      });
  }

  useEffect(() => {
    isAuth();
  }, []);
  console.log(isAuthenticated);
  return (
    <AuthContext.Provider
      value={{ isAuthenticated, setIsAuthenticated, setAuth }}
    >
      {props.children}
    </AuthContext.Provider>
  );
};

export default AuthContextProvider;

然后,我将路由 Package 在app.js中的提供程序中

import React from "react";
import {
  Switch,
  Route,
} from "react-router-dom";
import "./App.css";
import Register from "./components/pages/register";
import AuthContextProvider from "./components/context/authContext";
import RegisterRoutes from "./components/routing/registerRoutes";

function App() {

  return (
    <AuthContextProvider>
      <div className="App h-100 ">
        <Switch>
          <Route
            exact
            path="/register"
            render={(props) => (
              <RegisterRoutes {...props} />
            )}
          />
        </Switch>
      </div>
    </AuthContextProvider>
  );
}

export default App;

然后,我有一个RegisterRoutes组件,它根据isAuthenticated值返回两个页面中的一个

import React, { useContext } from "react";
import AuthContext from "../context/authContext";
import { Redirect } from "react-router-dom";
import Register from "../pages/register";

function RegisterRoutes(props) {
  const { isAuthenticated, setAuth } = useContext(AuthContext);
  console.log(isAuthenticated);

  return !isAuthenticated ? (
    <Register {...props} setAuth={setAuth} />
  ) : (
    <Redirect to="/login" />
  );
}

export default RegisterRoutes;
30byixjq

30byixjq1#

默认导出为AuthContextProvider(组件),而不是AuthContext(上下文对象):这不会像你期望的那样工作。此外,你正在尝试导出另一个对象中的上下文对象:

// WRONG: export context inside {}
const AuthContext = createContext();
export { AuthContext };

溶液1

而是正常导出上下文变量(不作为默认值):

// Export the variable
export const AuthContext = createContext();

// This works
import { AuthContext } from "../context/authContext";

方案2(推荐)

更好的做法是将上下文保存在单独的文件中,并将其导出为默认值:

// File AuthContext.js

import React, { createContext } from "react";

const AuthContext = createContext();

export default AuthContext;

// Import it in another file
import AuthContext from "./AuthContext.js";
cbeh67ev

cbeh67ev2#

我通过做一件简单的事情解决了这个问题。在index中,react-app,只需将我的提供程序涉及我的应用程序。

ReactDOM.render(
  <React.StrictMode>
    <AuthProvider>
      <App />
    </AuthProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

当我尝试在localStorage中设置日志记录时,也遇到了同样的问题。

a2mppw5e

a2mppw5e3#

对于在页面组件中使用gatsby和上下文API的用户:
你需要用gatsby-browser.jsgatsby-ssr.js中的上下文提供程序 Package 根元素。
示例:

import React from 'react';

import { CustomProvider } from './src/context/CustomProvider';

export const wrapRootElement = ({ element }) => {
  return <CustomProvider>{element}</CustomProvider>;
};
ikfrs5lh

ikfrs5lh4#

尝试在App.js中定义provider中的值= {{state,dispatch}}

<UserContext.Provider value ={{state, dispatch}}>
        <Routing/>
      </UserContext.Provider>
5sxhfpxr

5sxhfpxr5#

你必须把这个{}用于在发送过程中在其他文件中写入上下文

import {AuthContext} from "../context/authContext";

import { Redirect } from "react-router-dom";

import Register from "../pages/register";

function RegisterRoutes(props) {

  const { isAuthenticated, setAuth } = useContext(AuthContext);
ippsafx7

ippsafx76#

在我的App.js文件中添加AuthState后,我的错误得到了解决。

import { Routes, Route } from "react-router-dom";
import { BrowserRouter as Router } from "react-router-dom";
import Home from "./screens/Home";
import "./index.css";

import Register from "./components/Register";
import Login from "./components/Login";
import AuthState from "./context/auth/AuthState";
function App() {
  return (
    <>
      <AuthState>
          <Router>
            <Navbar />
            <Routes>
              <Route exact path="/" element={<Home />} />
              <Route exact path="/register" element={<Register />} />
              <Route exact path="/login" element={<Login />} />
            </Routes>
          </Router>
      </AuthState>
    </>
  );
}

export default App;
lx0bsm1f

lx0bsm1f7#

这是我解决它的方法,用authProvider将所有组件 Package 在app.js文件中。

相关问题