javascript - 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}/>
解决方案
您可以将道具传递给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"
推荐阅读
- symfony - Symfony 4 - 使用 multipart/form-data 发送 POST 请求
- c - 合并排序和递归
- elasticsearch - Elasticsearch 多个建议以及更高级的案例,例如在句子中间匹配前缀
- c# - 在列表视图中获取多个相同条目
- c# - C# 中属性的 Lambda 表达式
- pagespeed - 过去几周提供虚假信息的 PageSpeed 分数
- git - 如何将两个 git 提交者合并到一个 GitLab 帐户中?
- python - PostgreSQL 查询给出了意想不到的结果
- docker - 从 dockerfile 运行 OCI CLI 命令
- c# - 使用 MS Graph 库发送带有大附件的电子邮件