使用HOC进行身份验证

时间:2020-06-08 01:46:44

标签: javascript reactjs authentication react-router react-hoc

如果用户未通过身份验证,并且我正尝试使用HOC在前端检查身份验证,则服务器发送401响应,如Performing Authentication on Routes with react-router-v4中所示。 但是,我在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);

2 个答案:

答案 0 :(得分:1)

我可以想到一些可能性:

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

  1. 尝试删除{React}处的花括号,
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(我现在无法测试,因此我不太确定)。 / li>

尝试以下方法:

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

或者,如果不起作用,请在外部定义功能组件,然后传递到Route

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

答案 1 :(得分:0)

尝试这样做:

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