我正在構(gòu)建一個(gè) React 應(yīng)用程序并處理它的用戶身份驗(yàn)證。目前我正在使用來(lái)自“react-router-dom”的 BrowserRouter 來(lái)管理我的應(yīng)用程序中的路由。我有一個(gè)注冊(cè)路由,所有其他路由組件都包含在一個(gè)函數(shù)“withAuth”中。'withAuth' 的作用是查看應(yīng)用程序是否對(duì)使用進(jìn)行了身份驗(yàn)證。如果用戶通過(guò)身份驗(yàn)證,組件應(yīng)該加載(問(wèn)題在這里!)否則它應(yīng)該被重定向到登錄組件(工作正常?。?。當(dāng)應(yīng)用程序重定向到組件包含在“withAuth”函數(shù)中的路徑時(shí),登錄后。我收到以下錯(cuò)誤:TypeError: Object(...) is not a function (anonymous function) F:/Projects/beyouplus/beyouplus/beyouplus-client/src/services/auth.service.js:1411 | 返回 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 Screensimport SignInScreen from './components/SignInScreen'import DepartmentScreen from './components/DepartmentScreen'// Import Servicesimport { 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)
在 React Component 上使用包裝函數(shù)以使用瀏覽器路由器驗(yàn)證用戶登錄時(shí)如何修復(fù)
一只萌萌小番薯
2021-06-21 17:30:01