Javascript 为什么在条件路由中未定义this.props

Javascript 为什么在条件路由中未定义this.props,javascript,reactjs,routing,react-router,Javascript,Reactjs,Routing,React Router,我正试图通过创建一个ProtectedRoute组件来创建一个条件路由,如的所选答案所述 该条件来自传递到ProtectedRoute组件的道具。请查看下面的组件和路由代码 import React, {Component} from "react"; import { Route } from 'react-router-dom'; import { Redirect } from 'react-router'; class ProtectedRoute extends

我正试图通过创建一个
ProtectedRoute
组件来创建一个条件路由,如的所选答案所述

该条件来自传递到
ProtectedRoute
组件的道具。请查看下面的组件和路由代码

import React, {Component} from "react";
import { Route } from 'react-router-dom';
import { Redirect } from 'react-router';

class ProtectedRoute extends Component {
    render() {
      const { component: Component, ...props } = this.props
  
      return (
        <Route 
          {...props} 
          render={props => (
            this.props.profile.name === "admin" ?
              <Component {...props} /> :
              <Redirect to='/login' />
          )} 
        />
      )
    }
  }
export default ProtectedRoute;
运行上述应用程序时遇到的错误是:
TypeError:\u this2.props.po文件未定义
。但是,当我放置
路由
而不是
受保护路由
时,即
}/>

应用程序按预期工作


有人能帮我指出我做错了什么吗?非常感谢。

关于此错误
TypeError:\u此2.props.po文件未定义
它是
pofile
而不是
profile


有些地方你可能定义了错误的打字错误

此2.props.po文件未定义的原因-您尚未将其传递给
ProtectedRoute
组件,但已将其传递给
仪表板

通过它的正确方法是:

<ProtectedRoute path="/dashboard" profile={this.props.profile} component={props => <Dashboard profile={this.props.profile} />} />
}/>
顺便说一句,将JSX作为道具传递不是最好的做法,最好是作为孩子传递:

<ProtectedRoute path="/dashboard" profile={this.props.profile}>
  <Dashboard profile={this.props.profile} />
</ProtectedRoute>


然后在
ProtectedRoute
render
{this.props.children}
内部
Route
render
属性中,您使用了一个箭头函数,这意味着它内部的上下文绑定到
ProtectedRoute
的实例
this.props
inside
render
解析为
ProtectedRoute
的props。要解决此问题,您需要将
profile
传递到
ProtectedRoute
而不是
仪表板

<main>
  <Route path="/" exact component={props => <Home/>} />
  <ProtectedRoute path="/dashboard" profile={this.props.profile} component={props => <Dashboard />} />
</main>

} />
} />
<main>
  <Route path="/" exact component={props => <Home/>} />
  <ProtectedRoute path="/dashboard" profile={this.props.profile} component={props => <Dashboard />} />
</main>