簡體   English   中英

這個React組件中發生了什么ES6魔法?

[英]What's ES6 magic is happening in this React Component?

我正在關注本教程https://serverless-stack.com/ ,我在https://serverless-stack.com/chapters/create-a-route-that-redirects.html

這引入了AuthenticatedRoute ,它檢查名為isAuthenticated的prop的值,以決定是否天氣呈現組件或重定向用戶login

import React from "react";
import { Route, Redirect } from "react-router-dom";

export default ({ component: C, props: cProps, ...rest }) =>
  <Route
    {...rest}
    render={props =>
      cProps.isAuthenticated
        ? <C {...props} {...cProps} />
        : <Redirect
            to={`/login?redirect=${props.location.pathname}${props.location
              .search}`}
          />}
  />;

我得到了它所取得的成就,但我不確定它是如何做到的。

有人可以向我解釋下面有什么問題嗎?

  • component: C
  • ...rest
  • <C {...props} {...cProps} />

AuthenticatedRoute是一個功能 (無狀態)組件 - 一個功能。

  1. 使用props作為第一個參數調用該組件,並且該行({ component: C, props: cProps, ...rest }) 解構道具,並將其中一些分配給變量。 component: C從props對象中提取component屬性,並將其分配給變量C

  2. ...rest ({ component: C, props: cProps, ...rest })ECMAScript的Object Rest / Spread Properties提議的一部分 ,你需要babel的Object rest spread變換才能在當前的瀏覽器中工作。 它從未分配給變量的所有對象屬性(其余)創建一個新對象。

  3. <C {...props} {...cProps} />是react的JSX spread屬性 ,它將所有對象( propscProps )屬性轉換為組件屬性(如寫入key = value)。 cPropsprops將覆蓋props的屬性,因為它們出現在props之后。

component:C - 在ES6中,如果未傳遞參數,則可以進行默認初始化。 這里的組件將默認為C.

...休息 - 使用ES6,您可以傳播數據結構的元素。 這里休息可以有渲染功能的路徑路徑。

- cprops和props的每個元素都作為屬性傳遞給C組件。 cProps中的道具將覆蓋道具后面出現的道具屬性。

在這種情況下, Authenticated Route被稱為High Order Component。 Authenticated Route包裹Route組件並有條件地返回component: C如果用戶已通過身份驗證,則為component: CRedirect組件。

  • componentAuthenticated Route一個簡單的道具,但它重命名為C ,因為反應組件必須大寫。
  • props: cProps它想要接收到組件的道具
  • props其一個Route渲染需要被應用到組件道具,其中所述渲染方法應該返回
  • ...rest它包含任何其他道具的物體,基本上是指Route
  • 關於{... someData}您已在評論中回答過上述問題

然后你可以簡單地使用<AuthenticatedRoute />包裝並根據上面寫的信息傳遞你需要的道具

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM