javascript 错误:未捕获类型错误:无法解构“...”的属性“...”,因为它为空

lf5gs5x2  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(112)

我试图从返回useContext(AuthContext)useAuth中解构onLogout函数,在这样做的时候,我在控制台中得到一个错误:
错误:未捕获类型错误:无法解构“useAuth(...)”的属性“onLogout”,因为它为Null。
App.js代码段:

import React, { createContext, useContext } from "react";
import { Navigate, Route, Routes, useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { logout, userLogin, userRegister } from "./features/cv";
import { cookieCutter } from "./utils/cookie";

const AuthContext = createContext(null);

const AuthProvider = ({ children }) => {
  const token = cookieCutter("token");
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const handleLogin = (data) => {
    dispatch(userLogin(data));
    navigate("/table");
  };

  const handleRegister = (data) => {
    dispatch(userRegister(data));
    navigate("/table");
  };

  const handleLogout = () => {
    dispatch(logout());
    navigate("/login");
  };

  const value = {
    token,
    onLogin: handleLogin,
    onRegister: handleRegister,
    onLogout: handleLogout,
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

const useAuth = () => {
  return useContext(AuthContext);
};

function App() {

  const ProtectedRoute = ({ children }) => {
    const { token } = useAuth();

    if (!token) {
      return <Navigate to="/login" replace />;
    }
    return children;
  };

  const userString = JSON.parse(cookieCutter("user") ?? "{}");
  const { onLogout } = useAuth();

  return ( 
    <AuthProvider>
      <div>
        <Routes>
          <Route
            path="/"
            element={
              <ProtectedRoute>
                <Create />
              </ProtectedRoute>
            }
          />
          <Route
            path="/table"
            element={
              <ProtectedRoute>
                <Table />
              </ProtectedRoute>
            }
          />
          <Route
            path="/preview"
            element={
              <ProtectedRoute>
                <Preview />
              </ProtectedRoute>
            }
          />
          <Route path="/login" element={<Login />} />
          <Route path="/register" element={<Register />} />
        </Routes>
      </div>
    </AuthProvider>
 )

但是当我在ProtectedRoute函数中做同样的事情来获取令牌时,它没有任何错误,不知道为什么。
App.js ProtectedRoute函数:

const ProtectedRoute = ({ children }) => {
    const { token } = useAuth();

    if (!token) {
      return <Navigate to="/login" replace />;
    }
    return children;
  };
mu0hgdu0

mu0hgdu01#

你不能在App中使用useAuth(),因为它不是AuthProvider的子级。要做到这一点,请将AuthProvider调用移动到index文件中,以获得如下内容:

<AuthProvider>
  <App/>
</AuthProvider>

另外,在另一个组件中定义一个组件是不正确的。将ProtectedRoute移动到App之外:

const ProtectedRoute = ({ children }) => {
  const { token } = useAuth();

  if (!token) {
    return <Navigate to="/login" replace />;
  }
  return children;
};

相关问题