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



我正在尝试通过创建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} />} />
时,应用程序按预期工作。

有人可以帮我指出我做错了什么吗?这将不胜感激。

Routerender属性中,你使用了一个箭头函数,这意味着它里面的上下文绑定到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

也许有些地方你定义了错误的错别字。

最新更新