0

如果用户未通过身份验证,服务器将发送 401 响应,并且我尝试使用 HOC 在前端检查身份验证,如使用 react-router-v4 在路由上执行身份验证中所示。但是,我TypeError: Cannot read property 'Component' of undefined在 RequireAuth 中收到一条错误消息

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 }

应用程序.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);

4

2 回答 2

1

我可以想到一些可能性:

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

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

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


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

在 App.js 中,使用 Component 以大写字母开头

<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}/>
于 2020-06-08T01:55:53.117 回答
0

尝试这样做:

const RequireAuth = ({ component: Component }) => {}
于 2020-06-08T02:29:42.350 回答