gpt4 book ai didi

javascript - 使用 protected 路由时如何将 Prop 传递给子组件?

转载 作者:行者123 更新时间:2023-11-30 06:15:40 25 4
gpt4 key购买 nike

我目前正在使用 ReactJS 开发“火车票预订系统”。由于用户需要登录才能访问服务,因此我使用了 protected 路由来呈现一些组件。而不是使用默认的 .到目前为止,我知道如何使用 render 方法发送 Prop 。我想知道如何在使用 protected 路线时发送 Prop 。由于 render 方法不适用于该方法。

这是我对 protected 路由的实现。

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;

这就是我使用 protected 路线进行导航的方式

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

最佳答案

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

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

获取组件中的页面属性

因为你已经使用了解构。

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

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

所以你可以从变量 rest 中获取 props,它是一个对象。

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

关于javascript - 使用 protected 路由时如何将 Prop 传递给子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56345612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com