首页 > 解决方案 > How to pass props to child components when using protected routes?

问题描述

I'm currently developing a 'Train Ticket Reservation System' using ReactJS. Since users should login to access the services, I have used protected routes to render some components. Instead of using the default . So far I know how to send props with using the render method. I want to know how to send props when using protected routes. Since the render method doesn't work with that.

This is my implementation of the protected route.

import React from 'react';  
import auth from './auth';  
import {Route, Redirect} from 'react-router-dom';  

const ProtectedRoute = ({component: Component, ...rest}) => {  

    return(  
        <Route {...rest} render={props => {  

            if(auth.isAuthenticated()){  
                console.log(auth.isAuthenticated())  
                return <Component {...props}/>  
            }  
            else{  
                return <Redirect to={  
                    {  
                        pathname: '/',  
                        state:{  
                            from: props.location  
                        }  
                    }  
                } />  
            }  
            }} />  
    );  

};  

export default ProtectedRoute; 

This is how I used protected route for navigation

<ProtectedRoute  exact path="/Home/AboutUs" component={AboutUs}/>

标签: javascriptreactjsreact-router-dom

解决方案


您可以将道具传递给ProtectedRoute组件。

IE

<ProtectedRoute exact page="Home" path="/Home/AboutUs" component={AboutUs}/>

获取组件中的页面道具

由于您使用了解构。

const ProtectedRoute = ({component: Component, ...rest}) => { ..... }

除了props,其余的 props在扩展运算符之后component分配给变量。rest

rest因此,您可以从作为对象的变量中获取道具。

<Component {...props} pageProps={rest.page} />  // pageProps="Home"

推荐阅读