我是新来的 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/