如何使用带有钩子的上下文进行身份验证?

用户昵称

我正在尝试context用于处理我的应用程序中的身份验证。遇到了问题,因为我试图useContext在我的 之外调用Context.Provider,所以我将逻辑移到提供程序的子组件中。

现在我在TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))调用useContext子组件时收到一条错误消息问题真的是从上下文或其他东西中获取值吗?

app.js

import AuthContextProvider from "./components/context/authContext";
import RegisterRoutes from "./components/routing/registerRoutes";

function App() {
   return (
      <AuthContextProvider>
          <Route
            exact
            path="/register"
            render={(props) => (
              <RegisterRoutes {...props} />
            )}
          />
      </AuthContextProvider>
   )
}

在我的 authContext.js

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

export const AuthContext = createContext();

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

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

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

  useEffect(() => {
    isAuth();
  }, []);

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

export default AuthContextProvider;

在我的 registerRoutes.js

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

function RegisterRoutes(props) {
  const [isAuthenticated, setAuth] = useContext(AuthContext);

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

export default RegisterRoutes;
贾斯汀米切尔

正如错误所说,Context.ProviderinauthContext.js值不可迭代:

<AuthContext.Provider value={[isAuthenticated, setIsAuthenticated, setAuth]}>

传递给提供者的值需要是一个可迭代的值,在本例中是一个有效的 JSON 对象,而不是您提供的数组。因此,我们将其更改为:

<AuthContext.Provider value={{isAuthenticated, setIsAuthenticated, setAuth}}>

然后您更改引用registerRoutes.js以正确使用新结构:

const [isAuthenticated, setAuth] = useContext(AuthContext);

变成

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

瞧!您的 Context.Provider 值是可迭代的,您可以在应用程序中使用它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用请求和上下文进行身份验证

使用私有路由和上下文进行身份验证

使用Spring的请求范围上下文进行身份验证

使用上下文 API 进行身份验证,继续重定向到登录页面

使用身份验证作为上下文RESTful吗?

使用React上下文的用户身份验证

使用.Net Core 2和Moq,如何设置HTTP上下文以伪造身份验证?

如何在http.Request中使用golang 1.7上下文(用于身份验证)

Next.js - 如何使用 Provider 来包装路由并使用带有钩子的上下文

是否可以在其他上下文中使用带有响应(钩子)的上下文?

React身份验证上下文最初为空

在Spring Security上下文中,身份验证和授权有什么区别?

如何自定义Django Rest身份验证电子邮件上下文

React / Firebase如何检查身份验证(导入或上下文)?

如何在 JSF 上下文中替换经过身份验证的 javax.security.Principal?

使用自定义上下文从数据库身份验证中获取值

使用带有节点的Azure AD进行身份验证

REST API批处理-401未经授权(未在预期的上下文中对用户进行身份验证)

如何使用带有Web身份验证的apache httpclient进行http发布?

在React App(TypeScript)中设置上下文API,并将身份验证状态传递给所有组件

使用上下文传递身份验证详细信息时元素类型无效

如何通过钩子获取上下文

如何在静态上下文中使用带有上下文参数的类而不引起内存泄漏?

使用带有复杂对象的钩子设置提供程序值时,无法更新上下文状态

如何使用Devise对所有页面进行身份验证?

AuthenticationCredentialsNotFoundException:在安全上下文中未找到身份验证对象

Spring安全上下文手动身份验证给出奇怪的结果

Microsoft Graph API BadRequest当前经过身份验证的上下文无效

FIWARE:物联网代理和上下文代理之间的身份验证