【问题标题】:How to pass props to child components when using protected routes?使用受保护路由时如何将道具传递给子组件?
【发布时间】:2019-05-28 15:32:51
【问题描述】:

我目前正在使用 ReactJS 开发“火车票预订系统”。由于用户应该登录才能访问服务,因此我使用受保护的路由来呈现一些组件。而不是使用默认的 .到目前为止,我知道如何使用 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}/>

【问题讨论】:

    标签: javascript reactjs react-router-dom


    【解决方案1】:

    您可以将 props 传递给 ProtectedRoute 组件。

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

    在组件中获取页面道具

    因为你使用了解构。

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

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

    所以你可以从变量rest 中获取道具,这是一个对象。

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

    【讨论】:

      猜你喜欢
      • 2018-08-09
      • 2020-03-12
      • 2016-09-30
      • 2020-03-26
      • 1970-01-01
      • 2015-09-01
      • 2020-04-15
      • 1970-01-01
      相关资源
      最近更新 更多