我需要使用路由器将props传递给组件 . 这是我的代码:
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import AppBarTop from './appbar/AppBarTop';
import Login from '../pages/login/Login';
import {BrowserRouter as Router, Route} from 'react-router-dom';
class App extends Component {
render() {
const { isAuthenticated } = this.props;
return (
<Router>
<div>
<AppBarTop isAuthenticated={isAuthenticated} />
<div className="content">
<Route path="/login" isAuthenticated={isAuthenticated} component={Login} />
</div>
</div>
</Router>
);
}
}
如您所见,isAuthenticated我要传递给Login组件的prop .
class Login extends Component {
constructor(props) {
super(props);
console.log(props);
}
render() {
return (
<LoginForm />
);
}
}
export default connect(null) (Login);
当我记录道具时, isAuthenticated 道具不存在 . 我做错了什么?我怎样才能正确通过道具?我跟着文档和其他讨论 . 从我的理解,它应该工作 . react-router 和 react-router-dom 的版本是 4.0.0
1 回答
像这样传递:
它应该由登录组件中的
this.props.isAuthenticated
提供 .Reason of :
如果我们不写这个,那么只有
isAuthenticated
将被传递给Login组件,路由器传递给组件的所有其他值将不会在Login组件中可用 . 当我们写{...props}
时,我们传递所有值一个额外的值 .而不是使用
component
与路由器使用render
方法 .根据DOC:
Component:
Render: