2020/08/21

Destructuring assignment at REACT Function Component

 

React 學習時一定要記得一個概念,它就是 JavaScript,不管看到什麼,或是沒看到什麼,它就是 JavaScript,而且是支援最新標準的 JavaScript。

為什麼會這樣說?是因為要有 ES6 的概念,看 React 程式碼才有機會看懂!例如,今天要說的主題:【解構賦值(Destructuring Assignment)】。



在 React Function Component 裡,會用到一個經常被用到,但被列在 JavaScript 基礎課程的功能:Destructuring Assignment,中文翻譯為【解構賦值】。

根據【從 ES6 開始的 JavaScript 學習生活 -- 解構賦值】一節提到原文是:

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

其中也說到它的翻譯依據是:

destructuring: 變性、破壞性。使用"解構"是對照de-字頭有"脫離"、"去除"的意思。

assignment: 賦值、指派。賦值通常指的是程式中使用等號(=)運算符的語句。

原文指的是鏡射,也就類似像字典(Directory)對照的方式作表達式的對照,如下圖所示:


依解構賦值方式可分為三類:

  1. 從陣列解構賦值(Array destructuring)
  2. 從物件解構賦值(Object destructuring)
  3. 其它解構賦值

從陣列解構賦值(Array destructuring)

1
2
3
4
let a, b, rest;
[a, b] = [10, 20];
console.log(a); // 10
console.log(b); // 20

記得!解構賦值的最外圍的型態一定要對應,才符合鏡射的概念。

上述是基本款,另一種就類似解壓縮技術:

1
2
3
4
const x = [1, 2, 3, 4, 5];
const [y, z] = x;
console.log(y); // 1
console.log(z); // 2

陣列形式的解構賦值完全就是按照順序給值,不足的變數不給值,過多的變數會送 undefined

從物件解構賦值(Object destructuring)

1
2
3
4
5
const o = {p: 42, q: true};
const {q, p} = o;

console.log(p); // 42
console.log(q); // true 

可以看到,一樣是解壓縮,這次是完全對應名稱給值,而非按順序。

其它解構賦值

其它解構賦值也就是所謂的例外情況,請參閱文末參考連結。

解構賦值可以用在 React 什麼地方?

解構賦值在 React 上經常被應用到,最常見的是用在 props 上,如以下範例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const Count = (props) => {
  const children = props.children
  const firstName = props.firstName
  const lastName = props.lastName
  return (
    <div>
      <h1>{children}</h1>
      <label>{lastName} {firstName}</label>
    </div>
  )
};

const App = () => {
  const firstName = 'Wu'
  const lastName = 'Eden'
  return (
    <div>
       <Count firstName={firstName} lastName={lastName}> Hello, World </Count>
    </div>
  );
};


ReactDOM.render(
  <App />,
  document.getElementById('container')
);

這個範例中可以看到在 Count 物件程式碼,第 2 ~ 4 行敍述對 props 屬性進行一個【物件取值】的動作。

children 為 React 關鍵字,它所代表的是【標籤中間的東西】,以此例來說是第 18 行 Hello, World 的內容。

從範例也可以得知 props 屬於一種物件格式,適用在【解構賦值】的【從物件解構賦值】場合,Count 元件修改之後如下:

1
2
3
4
5
6
7
8
9
const Count = ( props ) => {
  const { firstName, lastName, children } = props
  return (
    <div>
      <h1>{children}</h1>
      <label>{lastName} {firstName}</label>
    </div>
  )
};

可以看到 props 被解構賦值地分配到 const 變數,這是顯式用法,再進階一點的隱式用法:

1
2
3
4
5
6
7
8
const Count = ({ firstName, lastName, children }) => {
  return (
    <div>
      <h1>{children}</h1>
      <label>{lastName} {firstName}</label>
    </div>
  )
};

第 1 行的【{ firstName, lastName, children }】原型為:

{firstName, lastName, children} = props

被濃縮得很厲害,經過一番拆解後是不是更加明瞭了呢!

結語

解構賦值是 ES6 的標準之一,React 非常吃 JavaScript 標準,網路上許多 React 範例都會使用,但未必會詳細說明,透過以上的小範例學習後,想必能看懂線上更多的 React 程式碼了。

以上和你分享。

See also

沒有留言:

張貼留言