javascript – React react-router-dom将props传递给组件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – React react-router-dom将props传递给组件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1919字,纯文字阅读大概需要3分钟。
内容图文
我需要使用路由器将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
解决方法:
像这样传递:
<Route
path="/login"
render={(props) => <Login {...props} isAuthenticated={isAuthenticated}/>}
/>
它应该由Login.props.isAuthenticated在Login Component中提供.
{… props}的原因:
如果我们不写这个,那么只有isAuthenticated将被传递给Login组件,路由器传递给组件的所有其他值将不会在Login组件中可用.当我们写{… props}时,我们将所有值传递给一个额外的值.
而不是使用带路由器的组件使用render方法.
按照DOC:
When you use component (instead of render or children, below) the
router uses React.createElement to create a new React element from the
given component. That means if you provide an inline function to the
component attribute, you would create a new component every render.
This results in the existing component unmounting and the new
component mounting instead of just updating the existing component.
When using an inline function for inline rendering, use the render.
This allows for convenient inline rendering and wrapping without the
undesired remounting.
内容总结
以上是互联网集市为您收集整理的javascript – React react-router-dom将props传递给组件全部内容,希望文章能够帮你解决javascript – React react-router-dom将props传递给组件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。