简体   繁体   English

反应保护路由

[英]React protected route

I have the following code :我有以下代码:

const PrivateRoute = ({ component: Component, ...rest }) => {
  return (<Route {...rest} render={(props) => (isAuthenticated() === true ? <Component {...props} /> : <Redirect to='/login' /> )} />)
}

but i dont understand how this works.. I call it like :但我不明白这是如何工作的..我称之为:

<PrivateRoute exact path = '/home' component={Home}></PrivateRoute>

it works , I just dont understand it.它有效,我只是不明白。 Where is props being passed in ? props 是从哪里传入的? What is component: Component.什么是组件:组件。

I would appreciate if someone could explain how this components works.如果有人能解释这个组件是如何工作的,我将不胜感激。

component: Component is object destructuring component: Component对象解构

You could re write it in the following way:您可以通过以下方式重新编写它:

const PrivateRoute = (props) => {
  const Component = props.component;
  //shallow copy props, can also do {...props}
  const rest = Object.assign({},props);
  //delete component property from rest
  //  this will not affect props becaus of the shallow copy

The react-router Route component will take a props.component and renders that component with all props passed to Route minus the props.component. react-router Route 组件将采用 props.component 并渲染该组件,并使用传递给 Route 的所有 props 减去 props.component。

You create a PrivateRoute that does the same but instead of rendering the component passed in props directly, it will render Route and pass a render prop to it that is a component created on the fly ()=>jsx .您创建一个PrivateRoute来执行相同的操作,但不是直接渲染在 props 中传递的组件,它会渲染 Route 并将渲染 prop 传递给它,这是一个动态创建的组件()=>jsx Route will render this component for you. Route 会为你渲染这个组件。

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

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