React技巧之中斷map迴圈

chuck發表於2022-07-01

原文連結:https://bobbyhadz.com/blog/react-map-break

作者:Borislav Hadzhiev

正文從這開始~

總覽

在React中,中斷map()迴圈:

  1. 在陣列上呼叫slice()方法,來得到陣列的一部分。
  2. 在部分陣列上呼叫map()方法。
  3. 遍歷部分陣列。
export default function App() {
  const employees = [
    {id: 1, name: 'Alice', country: 'Austria'},
    {id: 2, name: 'Bob', country: 'Belgium'},
    {id: 3, name: 'Carl', country: 'Canada'},
    {id: 4, name: 'Delilah', country: 'Denmark'},
    {id: 5, name: 'Ethan', country: 'Egypt'},
  ];

  // ?️ map() first 2 elements of array

  return (
    <div>
      {employees.slice(0, 2).map((employee, index) => {
        return (
          <div key={index}>
            <h2>name: {employee.name}</h2>
            <h2>country: {employee.country}</h2>

            <hr />
          </div>
        );
      })}
    </div>
  );
}

slice

Array.slice方法不會修改原陣列,相反,它會建立一個新陣列(原始陣列的淺拷貝)。

我們為slice()方法傳遞以下兩個引數:

名稱描述
startIndex新陣列中包含第一個元素的索引
endIndex到此為止,但不包含這個索引

我們指定了起始索引0,以及終止索引2。所以我們得到具有前兩個元素的部分陣列。

即使你提供給Array.slice方法的結束索引超過了陣列的長度,該方法並不會丟擲錯誤。但是會返回所有的陣列元素。
const arr = ['a', 'b', 'c'];

const first100 = arr.slice(0, 100);
console.log(first100); // ?️ ['a', 'b', 'c']

我們嘗試獲取陣列的前100個元素,該陣列只包含3個元素。因此新陣列包含原始陣列的所有3個元素。

filter

在呼叫map()之前,也可以使用Array.filter方法。

export default function App() {
  const employees = [
    {id: 1, name: 'Alice', country: 'Austria'},
    {id: 2, name: 'Bob', country: 'Belgium'},
    {id: 3, name: 'Carl', country: 'Canada'},
    {id: 4, name: 'Delilah', country: 'Denmark'},
    {id: 5, name: 'Ethan', country: 'Egypt'},
  ];

  // ?️ map() LAST 2 elements of array

  return (
    <div>
      {employees
        .filter(employee => {
          return (
            employee.country === 'Belgium' || employee.country === 'Denmark'
          );
        })
        .map((employee, index) => {
          return (
            <div key={index}>
              <h2>name: {employee.name}</h2>
              <h2>country: {employee.country}</h2>

              <hr />
            </div>
          );
        })}
    </div>
  );
}

我們傳遞給filter()方法的函式會被陣列中的每個元素呼叫。在每次迭代中,我們檢查當前物件是否有country屬性等於Belgium或者Denmark ,並返回比較的結果。

filter()方法返回一個陣列,其中只包含回撥函式返回真值的元素。

在本示例中,map()方法只會對id屬性值為2和4的物件呼叫。

負索引

如果你想在React中,對陣列的最後N個元素呼叫map方法,可以對Array.slice()方法傳遞負索引。

export default function App() {
  const employees = [
    {id: 1, name: 'Alice', country: 'Austria'},
    {id: 2, name: 'Bob', country: 'Belgium'},
    {id: 3, name: 'Carl', country: 'Canada'},
    {id: 4, name: 'Delilah', country: 'Denmark'},
    {id: 5, name: 'Ethan', country: 'Egypt'},
  ];

  // ?️ map() LAST 2 elements of array

  return (
    <div>
      {employees.slice(-2).map((employee, index) => {
        return (
          <div key={index}>
            <h2>name: {employee.name}</h2>
            <h2>country: {employee.country}</h2>

            <hr />
          </div>
        );
      })}
    </div>
  );
}

slice()方法傳遞負索引,表明從陣列尾部開始的偏移量。-2索引意味著給我陣列的最後兩個元素。這與對slice方法傳遞array.length - 2引數作用相同。

const arr = ['a', 'b', 'c', 'd', 'e'];

const last2 = arr.slice(-2);
console.log(last2); // ?️ ['d', 'e']

const last2Again = arr.slice(arr.length - 2);
console.log(last2Again); // ?️ ['d', 'e']

無論哪種方式,我們告訴slice方法,複製陣列的最後兩個元素,並將它們放置在一個新陣列中。

即使我們嘗試獲取更多陣列包含的元素,Array.slice也不會拋錯,相反它會返回一個包含所有元素的新陣列。

const arr = ['a', 'b', 'c'];

const last100 = arr.slice(-100);
console.log(last100); // ?️ ['a', 'b', 'c']

在這個例子中,我們試圖獲得一個只包含3個元素的陣列的最後100個元素,所以該陣列的所有元素都被複制到新的陣列中。

相關文章