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

标签 javascript reactjs routes react-router

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

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

最佳答案

Routerender 属性中,您使用箭头函数,这意味着其中的上下文绑定(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/

相关文章:

javascript - "Anonymous"合并 React 提供程序时添加的 HTML 元素

javascript - 将React与Electron一起使用

routes - Quasar 路线与登录页面不匹配

c# - 将 RouteData.Values 与操作参数结合起来

javascript - Google 跟踪代码管理器脚本会降低页面性能

javascript - 如何阻止子按钮触发 React 中的父链接?

javascript - 使用 Gulp 时如何将 React 设置为生产模式

javascript - 在 AngularJS 中使用 ui-router 进行路由

javascript - stacktrace.js 中的数字与什么相关?

javascript - `function (n) { .. }(jQuery)`是什么意思?