如果用户未经过身份验证,并且我尝试使用 HOC 在前端检查身份验证,则服务器将发送 401 响应,如使用 react-router-v4 对路由执行身份验证中所示。但是,我在“需要身份验证”中收到一个错误TypeError: Cannot read property 'Component' of undefined需要身份验证.jsimport {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 }应用.jsimport 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> );}}
2 回答
守候你守候我
TA贡献1802条经验 获得超10个赞
我可以想到一些可能性:
------- 将其移至顶部,最终修复了OP的问题-------
尝试在 处取下大括号。
{React}
import React from 'react';
------- 将其移至顶部,最终修复了OP的问题-------
在“需要身份验证.js”中,尝试
const RequireAuth = ({ Component }) => {} // changed from Component to { Component }
在 App.js中,使用以大写字母开头的组件
<Route exact path = '/' Component = {LandingPage}/>
另外,在 中,看起来你没有传入 React 组件,因为该函数没有返回 JSX(我现在无法测试,所以我不是很确定)。
<Route path="*" component = {() => "404 NOT FOUND"}/>
试试这个:
() => <div>404 NOT FOUND</div>
或者,如果它不起作用,则在外部定义一个功能组件并传递到 :Route
const NotFoundComponent = () => <div>404 NOT FOUND</div>
<Route path="*" component = {NotFoundComponent}/>
添加回答
举报
0/150
提交
取消