我正在尝试通过创建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;
以下是我如何在单独的侧面导航栏组件中实现路由。profile
对象作为 props 从App.js
传递给此组件。
<main>
<Route path="/" exact component={props => <Home/>} />
<ProtectedRoute path="/dashboard" component={props => <Dashboard profile={this.props.profile} />} />
</main>
运行上述应用程序时遇到的错误是:TypeError: _this2.props.pofile is undefined
.但是,当我放置一个Route
而不是ProtectedRoute
即<Route path="/dashboard" component={props => <Dashboard profile={this.props.profile} />} />
,
时,应用程序按预期工作。
有人可以帮我指出我做错了什么吗?这将不胜感激。
在Route
的render
属性中,你使用了一个箭头函数,这意味着它里面的上下文绑定到ProtectedRoute
的实例。 换句话说,this.props
内心render
决心使用ProtectedRoute
道具。要解决此问题,您需要将profile
传递给ProtectedRoute
而不是Dashboard
:
<main>
<Route path="/" exact component={props => <Home/>} />
<ProtectedRoute path="/dashboard" profile={this.props.profile} component={props => <Dashboard />} />
</main>
_this2.props.pofile is undefined
的原因 - 您尚未将其传递给ProtectedRoute
组件,但是,您将其传递给Dashboard
.
通过它的正确方法是:
<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
里面渲染{this.props.children}
.
在此错误TypeError: _this2.props.pofile is undefined
它是pofile
而不是profile
也许有些地方你定义了错误的错别字。