ReactJS - Map



JavaScript 的 Array 資料型別提供了一系列易於使用的函式來運算元組及其值。map() 就是這樣一個函式,它接受一個轉換函式,並透過應用轉換函式轉換給定陣列中的每個項來建立一個新陣列,並返回新建立的陣列。

map 函式的簽名如下所示:

array.map(function(item, index, items), thisValue)

這裡,

  • currentValue 指的是當前元素的值

  • index 指的是當前元素的索引值

  • items 指的是當前元素的陣列

  • thisValue 是可選的 this 值,可以在呼叫 map 函式時傳遞

假設我們有一系列數字,並希望將陣列中的每個值加倍。我們可以使用 map 函式在一行中完成此操作,如下所示:

var numbers = [2, 4, 6]
var transformed = numbers.map((val) => val + val)
for(var item of transformed) { console.log(item) }

這裡,輸出將如下所示:

4
8
12

示例

讓我們使用 create-react-app 建立一個新的應用程式並啟動它。

create-react-app myapp
cd myapp
npm start

接下來,在 components 資料夾下建立一個元件 ExpenseListUsingForLoop(src/components/ExpenseListUsingForLoop.js)。

import React from 'react'
class ExpenseListUsingForLoop extends React.Component {
   render() {
      return <table>
         <thead>
            <tr>
               <th>Item</th>
               <th>Amount</th>
            </tr>
         </thead>
         <tbody>
         </tbody>
         <tfoot>
            <tr>
               <th>Sum</th>
               <th></th>
            </tr>
         </tfoot>
      </table>
   }
}
export default ExpenseListUsingForLoop

在這裡,我們建立了一個帶有表頭和表尾的基本表格結構。

接下來,建立一個函式來查詢總支出金額。我們稍後將在 render 方法中使用它。

getTotalExpenses() {
   var items = this.props['expenses'];
   var total = 0;
   for(let i = 0; i < items.length; i++) {
      total += parseInt(items[i]);
   }
   return total;
}

這裡,getTotalExpenses 迴圈遍歷 expense 屬性並彙總總支出。

接下來,在 render 方法中新增支出項和總金額。

render() {
   var items = this.props['expenses'];
   var expenses = []
   expenses = items.map((item, idx) => <tr><td>item {idx + 1}</td><td>{item}</td></tr>)
   var total = this.getTotalExpenses();
   return <table>
      <thead>
         <tr>
            <th>Item</th>
            <th>Amount</th>
         </tr>
      </thead>
      <tbody>
         {expenses}
      </tbody>
      <tfoot>
         <tr>
            <th>Sum</th>
            <th>{total}</th>
         </tr>
      </tfoot>
   </table>
}

這裡我們有:

  • 使用 map 函式遍歷 expense 陣列中的每個項,為每個條目使用轉換函式建立表格行 (tr),最後將返回的陣列設定在 expenses 變數中。

  • 在 JSX 表示式中使用 expenses 陣列來包含生成的的行。

  • 使用 getTotalExpenses 方法查詢總支出金額並將其新增到 render 方法中。

ExpenseListUsingForLoop 元件的完整原始碼如下:

import React from 'react'
class ExpenseListUsingForLoop extends React.Component {
   getTotalExpenses() {
      var items = this.props['expenses'];
      var total = 0;
      for(let i = 0; i < items.length; i++) {
         total += parseInt(items[i]);
      }
      return total;
   }
   render() {
      var items = this.props['expenses'];
      var expenses = []
      expenses = items.map((item, idx) => <tr><td>item {idx + 1}</td><td>{item}</td></tr>)
      var total = this.getTotalExpenses();
      return <table>
         <thead>
            <tr>
               <th>Item</th>
               <th>Amount</th>
            </tr>
         </thead>
         <tbody>
            {expenses}
         </tbody>
         <tfoot>
            <tr>
               <th>Sum</th>
               <th>{total}</th>
            </tr>
         </tfoot>
      </table>
   }
}
export default ExpenseListUsingForLoop

接下來,使用 ExpenseListUsingForLoop 元件更新 App 元件 (App.js)。

import ExpenseListUsingForLoop from './components/ExpenseListUsingForLoop';
import './App.css';
function App() {
   var expenses = [100, 200, 300]
   return (
      <div>
         <ExpenseListUsingForLoop expenses={expenses} />
      </div>
   );
}
export default App;

接下來,在 App.css 中新增基本樣式。

/* Center tables for demo */
table {
   margin: 0 auto;
}
div {
   padding: 5px;
}
/* Default Table Style */
table {
   color: #333;
   background: white;
   border: 1px solid grey;
   font-size: 12pt;
   border-collapse: collapse;
}
table thead th,
table tfoot th {
   color: #777;
   background: rgba(0,0,0,.1);
   text-align: left;
}
table caption {
   padding:.5em;
}
table th,
table td {
   padding: .5em;
   border: 1px solid lightgrey;
}

最後,在瀏覽器中檢查應用程式。它將顯示如下所示的支出:

ReactJS Map

JSX 中的 Map

JSX 允許在其中包含任何 JavaScript 表示式。由於 map 只是 JavaScript 中的一個表示式,因此我們可以像下面這樣直接在 JSX 中使用它:

render() {
   var items = this.props['expenses'];
   var expenses = []
   
   // expenses = items.map((item, idx) => <tr><td>item {idx + 1}</td><td>{item}</td></tr>)
   var total = this.getTotalExpenses();
   return <table>
      <thead>
         <tr>
            <th>Item</th>
            <th>Amount</th>
         </tr>
      </thead>
      <tbody>
         {items.map((item, idx) => <tr><td>item {idx + 1}</td><td>{item}</td></tr>)}
      </tbody>
      <tfoot>
         <tr>
            <th>Sum</th>
            <th>{total}</th>
         </tr>
      </tfoot>
   </table>
}
export default ExpenseListUsingForLoop
廣告