React

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > React > React 状态数组删除元素

在 React 中如何从状态数组中删除一个元素

作者:迹忆客

这篇文章主要介绍了在 React 中从状态数组中删除一个元素,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

在 React 中从状态数组中删除一个元素:

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 中从状态数组中删除一个元素

我们使用 useState 挂钩初始化了一个员工状态变量。

我们传递给 Array.filter 方法的函数会针对数组中的每个元素进行调用。

在每次迭代中,我们检查对象的 id 属性是否不等于 2 并返回结果。

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 方法返回一个新数组,其中仅包含回调函数返回真值的元素。

如果从未满足条件,Array.filter 函数将返回一个空数组。

我们将一个函数传递给 setState,因为该函数可以保证以当前(最新)状态调用。

const removeSecond = () => {
  // 👇️ current 是当前状态数组
  setEmployees(current =>
    current.filter(employee => {
      return employee.id !== 2;
    }),
  );
};

当使用前一个状态计算下一个状态时,将一个函数传递给 setState

永远不要在 React 中改变状态数组

你不应该使用像 Array.pop()Array.splice() 这样的函数来改变 React 中的状态数组。

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

  // ⛔️ 不要这样做
  employees.splice(index, 1)

  // ⛔️ 或者这样也不好
  employees.pop()
};

状态对象和数组是不可变的。 为了让 React 跟踪变化,我们需要将状态设置为一个新数组,而不是修改原始数组。

根据多个条件从状态数组中删除元素

如果我们需要根据多个条件从状态数组中删除一个对象,请使用逻辑与 && 或逻辑或 || 运算符。

使用逻辑与 (&&) 运算符

逻辑与 && 运算符检查多个条件是否为真。

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 时,回调函数才返回 true。

使用逻辑或 (||) 运算符

逻辑 OR || 运算符检查是否至少有一个条件的计算结果为真。

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;
    }),
  );
};

两个条件中的任何一个都必须评估为要添加到新数组的元素的真值。

换句话说,如果对象的 name 属性等于 Fql 或 Carl,则该对象将被添加到新数组中。 所有其他对象都从数组中过滤掉。

使用两个运算符从状态数组中删除元素

如果我们必须检查多个复杂条件,也可以同时使用这两种运算符。

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';
    }),
  );
};

使用两个运算符从状态数组中删除元素

括号中的代码使用逻辑 OR || 运算符来检查 employee 对象的 name 属性是否是两个值之一。

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

如果满足条件,则逻辑与 && 运算符检查对象的国家/地区属性是否等于加拿大。

括号中的表达式必须计算为真,右侧的条件必须计算为真才能将对象保存在状态数组中。

从 React 中的 State 数组中删除重复项

要从状态数组中删除重复项:

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 数组中删除重复项

我们传递给 Set 构造函数的参数是一个可迭代的——在我们的例子中是一个数组。

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

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

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

!> 数组的所有元素都添加到新创建的集合中。 但是,Set 对象只能存储唯一值,因此会自动删除所有重复项。

最后一步是使用 Spread 运算符 ... 将 Set 的值解包到一个新数组中。

从 React 中的状态数组中删除重复对象

要从 React 中的状态数组中删除重复对象:

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 中的状态数组中删除重复对象

我们传递给 Array.filter 方法的函数被数组中的每个元素(对象)调用。

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 数组是否包含当前对象的 ID。

如果是这样,我们有一个副本。

如果不包含它,我们需要将 ID 添加到唯一 ID 数组并从函数返回一个真值。

如果传递给该方法的函数返回真值,则过滤器方法只会向结果数组添加一个元素。

uniqueEmployees 数组不包含任何重复项。

我们使用 id 属性作为对象的标识符。 但是,在您的情况下,对象的标识符可能被称为其他名称。

本质上,我们的解决方案是:

到此这篇关于在 React 中从状态数组中删除一个元素的文章就介绍到这了,更多相关React 状态数组删除一个元素内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文