简体   繁体   中英

React react-router-dom pass props to component

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 (
            <Router>
                <div>
                    <AppBarTop isAuthenticated={isAuthenticated} />
                    <div className="content">
                        <Route path="/login" isAuthenticated={isAuthenticated} component={Login} />
                    </div>
                </div>
            </Router>
        );
    }
}

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

}

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

Pass it like this:

<Route 
    path="/login" 
    render={(props) => <Login {...props} isAuthenticated={isAuthenticated}/>} 
/>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM