繁体   English   中英

使用受保护的路线时如何将道具传递给子组件?

[英]How to pass props to child components when using protected routes?

我目前正在使用ReactJS开发“火车票预订系统”。 由于用户应该登录才能访问服务,因此我使用了受保护的路由来渲染某些组件。 而不是使用默认值。 到目前为止,我知道如何使用render方法发送道具。 我想知道使用受保护路线时如何发送道具。 由于render方法不适用于该方法。

这是我对受保护路线的实现。

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; 

这就是我使用受保护的路线进行导航的方式

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

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

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

在组件中获取页面道具

由于您已经使用了解构。

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

component道具外,其余道具在点差算子之后分配给变量rest

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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