繁体   English   中英

使用 React 的受保护路由

[英]Protected Routes using React

浏览有关在 React 中创建受保护路由的资源,我遇到了以下示例

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

我可以通过

<PrivateRoute exact path="/books" component={Book} />

所以我对上面的代码段有以下疑问

  • 受保护的路由作为component传递,但为什么要使用Component标签?
  • 此外,如果属性的 rest 作为...rest传递到Route render方法从哪里获取其props

在 Javascript 中,我们可以在解构时使用冒号(:) 重命名键,如component:Component这样做的原因是我们不能直接解构Component ,因为它是 React 中的保留关键字。

2.

...rest是 Route 组件的道具。 例如:在<Route exact path="/books" component={Book} />中,'exact' 和 'path' 是 Route 组件的道具,而不是 Book。

要为 Book 组件传递 props,react-router 允许我们使用 render prop。 render prop 接受一个 function 并返回一个组件。 react-router 为我们处理从 Route 组件到 Book 组件的 props 传递。

暂无
暂无

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

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