最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

在?React?中如何從狀態(tài)數(shù)組中刪除一個元素

 更新時間:2023年03月24日 09:48:53   作者:跡憶客  
這篇文章主要介紹了在?React?中從狀態(tài)數(shù)組中刪除一個元素,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

在 React 中從狀態(tài)數(shù)組中刪除一個元素:

  • 使用 filter() 方法迭代數(shù)組。
  • 在每次迭代中,檢查是否滿足條件。
  • 將狀態(tài)設(shè)置為過濾器方法返回的新數(shù)組。
import {useState} from 'react';

export default function App() {
  const initialState = [
    {id: 1, name: 'Fql', country: 'Austria'},
    {id: 2, name: 'Jiyik', country: 'China'},
  ];

  const [employees, setEmployees] = useState(initialState);

  const removeSecond = () => {
    setEmployees(current =>
      current.filter(employee => {
        // ??? 刪除等于 2 的對象
        return employee.id !== 2;
      }),
    );
  };

  return (
    <div>
      <button onClick={removeSecond}>Remove second</button>

      {employees.map(({id, name, country}) => {
        return (
          <div key={id}>
            <h2>name: {name}</h2>
            <h2>country: {country}</h2>

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

React 中從狀態(tài)數(shù)組中刪除一個元素

我們使用 useState 掛鉤初始化了一個員工狀態(tài)變量。

我們傳遞給 Array.filter 方法的函數(shù)會針對數(shù)組中的每個元素進行調(diào)用。

在每次迭代中,我們檢查對象的 id 屬性是否不等于 2 并返回結(jié)果。

const initialState = [
  {id: 1, name: 'Fql', country: 'Austria'},
  {id: 2, name: 'Jiyik', country: 'China'},
];

const filtered = initialState.filter(obj => {
  // ??? 為所有 id 不等于 2 的元素返回真
  return obj.id !== 2;
});

// ??? [{id: 1, name: 'Fql', country: 'Austria'}]
console.log(filtered);

filter 方法返回一個新數(shù)組,其中僅包含回調(diào)函數(shù)返回真值的元素。

如果從未滿足條件,Array.filter 函數(shù)將返回一個空數(shù)組。

我們將一個函數(shù)傳遞給 setState,因為該函數(shù)可以保證以當前(最新)狀態(tài)調(diào)用。

const removeSecond = () => {
  // ??? current 是當前狀態(tài)數(shù)組
  setEmployees(current =>
    current.filter(employee => {
      return employee.id !== 2;
    }),
  );
};

當使用前一個狀態(tài)計算下一個狀態(tài)時,將一個函數(shù)傳遞給 setState。

永遠不要在 React 中改變狀態(tài)數(shù)組

你不應(yīng)該使用像 Array.pop()Array.splice() 這樣的函數(shù)來改變 React 中的狀態(tài)數(shù)組。

const removeSecond = () => {
  const index = employees.findIndex(emp => emp.id === 2)

  // ?? 不要這樣做
  employees.splice(index, 1)

  // ?? 或者這樣也不好
  employees.pop()
};

狀態(tài)對象和數(shù)組是不可變的。 為了讓 React 跟蹤變化,我們需要將狀態(tài)設(shè)置為一個新數(shù)組,而不是修改原始數(shù)組。

根據(jù)多個條件從狀態(tài)數(shù)組中刪除元素

如果我們需要根據(jù)多個條件從狀態(tài)數(shù)組中刪除一個對象,請使用邏輯與 && 或邏輯或 || 運算符。

使用邏輯與 (&&) 運算符

邏輯與 && 運算符檢查多個條件是否為真。

const initialState = [
  {id: 1, name: 'Fql', country: 'Austria'},
  {id: 2, name: 'Jiyik', country: 'China'},
  {id: 3, name: 'Carl', country: 'Austria'},
];

const [employees, setEmployees] = useState(initialState);

const remove = () => {
  setEmployees(current =>
    current.filter(employee => {
      return employee.id !== 3 && employee.id !== 2;
    }),
  );
};

邏輯與 && 運算符僅在兩個條件都為真時才計算為真。

僅當對象的 id 屬性不等于 3 且不等于 2 時,回調(diào)函數(shù)才返回 true。

使用邏輯或 (||) 運算符

邏輯 OR || 運算符檢查是否至少有一個條件的計算結(jié)果為真。

const initialState = [
  {id: 1, name: 'Fql', country: 'Austria'},
  {id: 2, name: 'Jiyik', country: 'China'},
  {id: 3, name: 'Carl', country: 'Austria'},
];

const [employees, setEmployees] = useState(initialState);

const remove = () => {
  setEmployees(current =>
    current.filter(employee => {
      return employee.id !== 3 && employee.id !== 2;
    }),
  );
};

兩個條件中的任何一個都必須評估為要添加到新數(shù)組的元素的真值。

換句話說,如果對象的 name 屬性等于 Fql 或 Carl,則該對象將被添加到新數(shù)組中。 所有其他對象都從數(shù)組中過濾掉。

使用兩個運算符從狀態(tài)數(shù)組中刪除元素

如果我們必須檢查多個復(fù)雜條件,也可以同時使用這兩種運算符。

const initialState = [
  {id: 1, name: 'Fql', country: 'Austria'},
  {id: 2, name: 'Jiyik', country: 'China'},
  {id: 3, name: 'Carl', country: 'Austria'},
];

const [employees, setEmployees] = useState(initialState);

const remove = () => {
  setEmployees(current =>
    current.filter(employee => {
      return employee.name === 'Fql' || employee.name === 'Carl';
    }),
  );
};

使用兩個運算符從狀態(tài)數(shù)組中刪除元素

括號中的代碼使用邏輯 OR || 運算符來檢查 employee 對象的 name 屬性是否是兩個值之一。

const remove = () => {
  setEmployees(current =>
    current.filter(employee => {
      return (
        (employee.name === 'Fql' ||
          employee.name === 'Carl') &&
        employee.country === 'Canada'
      );
    }),
  );
};

如果滿足條件,則邏輯與 && 運算符檢查對象的國家/地區(qū)屬性是否等于加拿大。

括號中的表達式必須計算為真,右側(cè)的條件必須計算為真才能將對象保存在狀態(tài)數(shù)組中。

從 React 中的 State 數(shù)組中刪除重復(fù)項

要從狀態(tài)數(shù)組中刪除重復(fù)項:

  • 使用 useState() 掛鉤將數(shù)組存儲在狀態(tài)中。
  • 使用 Set() 構(gòu)造函數(shù)從狀態(tài)數(shù)組中刪除重復(fù)項。
  • 將狀態(tài)數(shù)組更新為新值。
import {useState} from 'react';

const App = () => {
  const words = ['fql', 'fql', 'jiyik', 'jiyik', 'com'];
  const [state, setState] = useState(words);

  const withoutDuplicates = [...new Set(words)];

  // ??? ['fql', 'jiyik', 'com']
  console.log(withoutDuplicates);

  const removeDuplicates = () => {
    setState(prevState => [...new Set(prevState)]);
  };

  return (
    <div>
      <button onClick={removeDuplicates}>
        Remove duplicates
      </button>

      {state.map((word, index) => {
        return (
          <div key={index}>
            <h2>{word}</h2>
          </div>
        );
      })}
    </div>
  );
};

export default App;

從 React 中的 State 數(shù)組中刪除重復(fù)項

我們傳遞給 Set 構(gòu)造函數(shù)的參數(shù)是一個可迭代的——在我們的例子中是一個數(shù)組。

const words = ['fql', 'fql', 'jiyik', 'jiyik', 'com'];

// ??? {'fql', 'jiyik', 'com'}
console.log(new Set(words));

const withoutDuplicates = [...words];
console.log(withoutDuplicates); // ??? ['fql', 'jiyik', 'com']

!> 數(shù)組的所有元素都添加到新創(chuàng)建的集合中。 但是,Set 對象只能存儲唯一值,因此會自動刪除所有重復(fù)項。

最后一步是使用 Spread 運算符 ... 將 Set 的值解包到一個新數(shù)組中。

從 React 中的狀態(tài)數(shù)組中刪除重復(fù)對象

要從 React 中的狀態(tài)數(shù)組中刪除重復(fù)對象:

  • 創(chuàng)建一個將存儲唯一對象 ID 的空數(shù)組。
  • 使用 filter() 方法迭代狀態(tài)數(shù)組。
  • 檢查唯一 ID 數(shù)組是否包含當前對象的 ID。
  • 如果包含 ID,則將對象的 ID 添加到唯一 ID 數(shù)組并將對象添加到狀態(tài)數(shù)組。
import {useState} from 'react';

const App = () => {
  const employees = [
    {id: 1, name: 'Fql'},
    {id: 1, name: 'Fql'},
    {id: 2, name: 'Jiyik'},
    {id: 2, name: 'Jiyik'},
  ];

  const [state, setState] = useState(employees);

  const handleClick = () => {
    const uniqueIds = [];

    setState(currentState => {
      return currentState.filter(element => {
        const isDuplicate = uniqueIds.includes(element.id);

        if (!isDuplicate) {
          uniqueIds.push(element.id);

          return true;
        }

        return false;
      });
    });
  };

  return (
    <div>
      <button onClick={handleClick}>
        Remove duplicate objects
      </button>

      {state.map((employee, index) => {
        return (
          <div key={index}>
            <h2>id: {employee.id}</h2>
            <h2>name: {employee.name}</h2>
          </div>
        );
      })}
    </div>
  );
};

export default App;

從 React 中的狀態(tài)數(shù)組中刪除重復(fù)對象

我們傳遞給 Array.filter 方法的函數(shù)被數(shù)組中的每個元素(對象)調(diào)用。

const employees = [
  {id: 1, name: 'Fql'},
  {id: 1, name: 'Fql'},
  {id: 2, name: 'Jiyik'},
  {id: 2, name: 'Jiyik'},
];

const uniqueIds = [];

const uniqueEmployees = employees.filter(element => {
  const isDuplicate = uniqueIds.includes(element.id);

  if (!isDuplicate) {
    uniqueIds.push(element.id);

    return true;
  }

  return false;
});

console.log(uniqueEmployees);

在每次迭代中,我們檢查唯一 ID 數(shù)組是否包含當前對象的 ID。

如果是這樣,我們有一個副本。

如果不包含它,我們需要將 ID 添加到唯一 ID 數(shù)組并從函數(shù)返回一個真值。

如果傳遞給該方法的函數(shù)返回真值,則過濾器方法只會向結(jié)果數(shù)組添加一個元素。

uniqueEmployees 數(shù)組不包含任何重復(fù)項。

我們使用 id 屬性作為對象的標識符。 但是,在您的情況下,對象的標識符可能被稱為其他名稱。

本質(zhì)上,我們的解決方案是:

  • 僅將唯一 ID 添加到 uniqueIds 數(shù)組。
  • 如果對象的 ID 不在 uniqueIds 數(shù)組中,則僅將對象添加到結(jié)果數(shù)組。

到此這篇關(guān)于在 React 中從狀態(tài)數(shù)組中刪除一個元素的文章就介紹到這了,更多相關(guān)React 狀態(tài)數(shù)組刪除一個元素內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • react?cropper圖片裁切實例詳解

    react?cropper圖片裁切實例詳解

    這篇文章主要為大家介紹了react?cropper圖片裁切實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-11-11
  • 詳解React 和 Redux的關(guān)系

    詳解React 和 Redux的關(guān)系

    這篇文章主要為大家介紹了React 和 Redux的關(guān)系,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2021-11-11
  • react+antd 遞歸實現(xiàn)樹狀目錄操作

    react+antd 遞歸實現(xiàn)樹狀目錄操作

    這篇文章主要介紹了react+antd 遞歸實現(xiàn)樹狀目錄操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • react?fiber使用的關(guān)鍵特性及執(zhí)行階段詳解

    react?fiber使用的關(guān)鍵特性及執(zhí)行階段詳解

    這篇文章主要為大家介紹了react?fiber使用的關(guān)鍵特性及執(zhí)行階段詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-05-05
  • react項目如何運行在微信公眾號

    react項目如何運行在微信公眾號

    這篇文章主要介紹了react項目如何運行在微信公眾號,幫助大家更好的理解和學習使用react,感興趣的朋友可以了解下
    2021-04-04
  • 深入理解React調(diào)度(Scheduler)原理

    深入理解React調(diào)度(Scheduler)原理

    本文主要介紹了深入理解React調(diào)度(Scheduler)原理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • react中使用heatmap.js實現(xiàn)熱力圖的繪制

    react中使用heatmap.js實現(xiàn)熱力圖的繪制

    heatmap.js?是一個用于生成熱力圖的?JavaScript?庫,React?是一個流行的?JavaScript?庫,用于構(gòu)建用戶界面,本小編給大家介紹了在React?應(yīng)用程序中使用heatmap.js實現(xiàn)熱力圖的繪制的示例,文中通過代碼示例介紹的非常詳細,需要的朋友可以參考下
    2023-12-12
  • React+Redux實現(xiàn)簡單的待辦事項列表ToDoList

    React+Redux實現(xiàn)簡單的待辦事項列表ToDoList

    這篇文章主要為大家詳細介紹了React+Redux實現(xiàn)簡單的待辦事項列表ToDoList,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-09-09
  • React函數(shù)組件hook原理及構(gòu)建hook鏈表算法詳情

    React函數(shù)組件hook原理及構(gòu)建hook鏈表算法詳情

    這篇文章主要介紹了React函數(shù)組件hook原理及構(gòu)建hook鏈表算法詳情,每一個?hook?函數(shù)都有對應(yīng)的?hook?對象保存狀態(tài)信息,更多詳細分析,需要的朋友可以參考一下
    2022-07-07
  • 詳解react-router如何實現(xiàn)按需加載

    詳解react-router如何實現(xiàn)按需加載

    本篇文章主要介紹了react-router如何實現(xiàn)按需加載,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06

最新評論

大方县| 岳西县| 剑河县| 百色市| 怀来县| 肃北| 盱眙县| 新密市| 宜宾县| 兴城市| 邻水| 凯里市| 扎兰屯市| 浮梁县| 焦作市| 龙岩市| 视频| 黄龙县| 凤台县| 景德镇市| 凉城县| 六枝特区| 平谷区| 浦县| 通化县| 仁化县| 固阳县| 普定县| 南木林县| 永和县| 宁陵县| 平泉县| 宜良县| 屏边| 赫章县| 洪洞县| 大厂| 江山市| 大余县| 陇南市| 客服|