reactjs - React router-4 中未定义自定义 props

标签 reactjs

我是新来的 react 。我创建一条路线

<Switch>
    <Route path="/login" exact render={(props) => (<LoginPage test="hi" {...props}/>)} />
    <Route path="/dashboard" exact component={DashboardPage}/>
    <Route  component={LoginPage}/>
</Switch>

在 LoginPage 中,当我尝试使用 console.log(this.props.test) 时,它显示未定义。

请帮我看看我的路线有什么问题。

登录页面.js

import React from 'react';

import styles from './../styles/_login.css'

class LoginPage extends React.Component{

    constructor(props){
      super(props);
      this.handleLogin = this.handleLogin.bind(this);
      console.log(this.props.test)
    }

    componentDidMount(){
      console.log(this.props.test)
    }

    render(){
        return(
          <div>I am login form</div>
        )
    }
}

export default LoginPage;

最佳答案

不确定情况是否如此,但您有两条LoginPage路线。
这个:

Route path="/login" exact render={(props) => (<LoginPage test="hi" {...props}/>)} />

还有这个(没有传递任何 Prop ):

<Route  component={LoginPage}/>

我认为您走错了路线(确保您的网址中有 /login)。

你确定这是故意的吗?

编辑

The one without route path will be loaded by default

您没有将 test 作为 prop 传递给此路由,因此它显示为 undefined

关于reactjs - React router-4 中未定义自定义 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47236929/

相关文章:

javascript - Redux-Form 可重复字段

javascript - 如何确保 React props 的类型正确

css - 如何在构建语义 ui 时生成多个 semantic.<theme>.min.css 文件?

javascript - 需要关于我不断收到的 react.js 错误的帮助

javascript - 在 ReactJS 中更新数组中对象的最佳方法是什么?

reactjs - react 谷歌地图 : Super expression must either be null or a function, 不是未定义

css - 带有 React CSS 模块的 SASS 变量插值

reactjs - 如何使用 React 将视频文件上传到 S3 存储桶

javascript - 如何删除 Meteor 集合中数组中的某个字段?

javascript - 无法在输入框中输入密码