使用 HOC 响应身份验证

React Authentication using HOC

如果用户未通过身份验证,服务器将发送 401 响应,而我正尝试使用 HOC 在前端检查身份验证,如 中所示。 但是,我在 RequireAuth

中收到一条错误消息 TypeError: Cannot read property 'Component' of undefined

RequireAuth.js

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

const RequireAuth = (Component) => { 

    return class Apps extends React.Component { 
        state = {
            isAuthenticated: false,
            isLoading: true
        }

        async componentDidMount() {
            const url = '/getinfo'
            const json = await fetch(url, {method: 'GET'})
            if (json.status !== 401)    
                this.setState({isAuthenticated: true, isLoading: false})
            else
                console.log('not auth!')
        } 

        render() { 
           const { isAuthenticated, isLoading } = this.state;
           if(isLoading) {
               return <div>Loading...</div>
           }
           if(!isAuthenticated) {
               return <Redirect to="/" />
           }
           return <Component {...this.props} /> 
        }
    } 

} 

export { RequireAuth }

App.js

import React from 'react';
import { BrowserRouter as Router, Route, Switch, withRouter } from 'react-router-dom';
import SignIn from './SignIn'
import NavigationBar from './NavigationBar'
import LandingPage from './LandingPage'
import Profile from './Profile'
import Register from './Register'
import { RequireAuth } from './RequireAuth'

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() { 
  return (
    <div>
      <Router>
            <NavigationBar />
            <Switch>
              <Route exact path = '/'
                component = {LandingPage}
              />
              <Route exact path = '/register'
                component = {Register}
              />
              <Route exact path = '/profile' 
                component = {RequireAuth(Profile)}
              />
              <Route path="*" component = {() => "404 NOT FOUND"}/>
            </Switch>
      </Router>
    </div>
  );
}
}

export default withRouter(App);

我能想到一些可能性:

------ 将其移至顶部,最终解决了 OP 的问题 ------

  1. 尝试删除 {React}
  2. 处的大括号
import React from 'react';

------ 将其移至顶部,最终解决了 OP 的问题 ------


  1. 在RequireAuth.js中,尝试
const RequireAuth = ({ Component }) => {} // changed from Component to { Component }

在App.js中,使用以大写字母开头的组件

<Route exact path = '/' Component = {LandingPage}/>


  1. 此外,在 <Route path="*" component = {() => "404 NOT FOUND"}/> 中,您似乎没有传入 React 组件,因为函数没有返回 JSX(我现在无法测试,所以我不太确定) .

试试这个:

() => <div>404 NOT FOUND</div>

或者不行的话,在外部定义一个功能组件,传入Route:

const NotFoundComponent = () => <div>404 NOT FOUND</div>
<Route path="*" component = {NotFoundComponent}/>

尝试这样做:

const RequireAuth = ({ component: Component }) => {}