温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

React中怎么从状态数组中删除一个元素

发布时间:2023-03-24 10:57:00 来源:亿速云 阅读:152 作者:iii 栏目:开发技术

本文小编为大家详细介绍“React中怎么从状态数组中删除一个元素”,内容详细,步骤清晰,细节处理妥当,希望这篇“React中怎么从状态数组中删除一个元素”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

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

  • 使用 filter() 方法迭代数组。

  • 在每次迭代中,检查是否满足条件。

  • 将状态设置为过滤器方法返回的新数组。

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}>
            <h3>name: {name}</h3>
            <h3>country: {country}</h3>

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

React中怎么从状态数组中删除一个元素

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

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

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

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

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

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

  • 使用 useState() 挂钩将数组存储在状态中。

  • 使用 Set() 构造函数从状态数组中删除重复项。

  • 将状态数组更新为新值。

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}>
            <h3>{word}</h3>
          </div>
        );
      })}
    </div>
  );
};

export default App;

React中怎么从状态数组中删除一个元素

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

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

  • 创建一个将存储唯一对象 ID 的空数组。

  • 使用 filter() 方法迭代状态数组。

  • 检查唯一 ID 数组是否包含当前对象的 ID。

  • 如果包含 ID,则将对象的 ID 添加到唯一 ID 数组并将对象添加到状态数组。

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}>
            <h3>id: {employee.id}</h3>
            <h3>name: {employee.name}</h3>
          </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 属性作为对象的标识符。 但是,在您的情况下,对象的标识符可能被称为其他名称。

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

  • 仅将唯一 ID 添加到 uniqueIds 数组。

  • 如果对象的 ID 不在 uniqueIds 数组中,则仅将对象添加到结果数组。

读到这里,这篇“React中怎么从状态数组中删除一个元素”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI