React react-router-dom pass props to component

匿名 (未验证) 提交于 2019-12-03 08:30:34

问题:

I need to pass props to component using router. Here's my code:

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 (             
); } }

As you can see, isAuthenticated the prop i want to pass to Login component.

class Login extends Component {      constructor(props) {         super(props);         console.log(props);     }      render() {         return (                      );     }  }  export default connect(null) (Login); 

When i log the props the isAuthenticated prop is not there. What i'm doing wrong? How can i pass the prop correctly? I followed the docs and also other discussions. From my understanding it should work. The version of react-router and react-router-dom is 4.0.0

回答1:

Pass it like this:

}  /> 

It should be available by this.props.isAuthenticated in Login Component.

Reason of {...props}:

If we don't write this then only isAuthenticated will get passed to Login component, all other values that router passes to component, will not be available inside Login component. When we write {...props} then we are passing all the values with one extra value.

And instead of using component with router use render method.

As per DOC:

Component:

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.

Render:

This allows for convenient inline rendering and wrapping without the undesired remounting.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!