我正在尝试通过创建 ProtectedRoute
来创建条件路由所选答案 this question 所描述的组件.
条件来自传入 ProtectedRoute
的 props成分。请查看下面的组件和路由代码。
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
属性中,您使用箭头函数,这意味着其中的上下文绑定(bind)到 ProtectedRoute
的实例。换句话说,render
中的 this.props
解析为 ProtectedRoute
的 props。要解决此问题,您需要将 profile
传递给 ProtectedRoute
而不是 Dashboard
:
<main>
<Route path="/" exact component={props => <Home/>} />
<ProtectedRoute path="/dashboard" profile={this.props.profile} component={props => <Dashboard />} />
</main>
关于javascript - 为什么条件路由中 this.props 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52864418/