簡體   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