在 React Component 上使用包装函数以使用浏览器路由器验证用户登录时如何修复

我正在构建一个 React 应用程序并处理它的用户身份验证。目前我正在使用来自“react-router-dom”的 BrowserRouter 来管理我的应用程序中的路由。我有一个注册路由,所有其他路由组件都包含在一个函数“withAuth”中。'withAuth' 的作用是查看应用程序是否对使用进行了身份验证。如果用户通过身份验证,组件应该加载(问题在这里!)否则它应该被重定向到登录组件(工作正常!)。


当应用程序重定向到组件包含在“withAuth”函数中的路径时,登录后。我收到以下错误:


TypeError: Object(...) is not a function (anonymous function) F:/Projects/beyouplus/beyouplus/beyouplus-client/src/services/auth.service.js:14


11 | 返回 useContext(MyContext)


12 | }


13 |


>14 | export const withAuth = (Component) => (props) => {


15 | 如果 (!isSignedIn()) {


16 | if (props.history.location.pathname === '/sign-in') {


17 | 返回空值


我的 App.js:


import React from 'react';

import {

  BrowserRouter,

  Route,

  Redirect

} from 'react-router-dom'


// Import Screens

import SignInScreen from './components/SignInScreen'

import DepartmentScreen from './components/DepartmentScreen'


// Import Services

import { withAuth } from './services/auth.service'


const App = () => (

  <BrowserRouter>

    <Route exact path="/sign-in" component={SignInScreen}/>

    <Route exact path="/dept" component={withAuth(DepartmentScreen)}/>

    <Route exact path="/" render={redirectToDept} />

  </BrowserRouter>

)


const redirectToDept = () => (

  <Redirect to="/dept" />

)


export default App;

auth.service.js 文件:


import React, { useContext } from 'react'

import { Redirect } from 'react-router-dom'


import client from '../client'

import { getMeQuery } from '../graphql/queries'

import { useCacheService } from './cache.service'


const MyContext = React.createContext(null)


export const useMe = () => {

    return useContext(MyContext)

}


export const withAuth = (Component) => (props) => {

    if (!isSignedIn()) {

        if (props.history.location.pathname === '/sign-in') {

            return null

        }


        return (

            <Redirect to="/sign-in" />

        )

    }


    const { data, error, loading } = getMeQuery()


    useCacheService()


    if(loading) return null


    if(error || !data.me) {

        signOut()


        return <Redirect to="/sign-in" />

    }


    console.log(data.me)



一只萌萌小番薯
浏览 150回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript