前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >React技巧之移除状态数组中的对象

React技巧之移除状态数组中的对象

作者头像
chuckQu
发布2022-08-19 15:55:46
1.3K0
发布2022-08-19 15:55:46
举报
文章被收录于专栏:前端F2E

原文链接:https://bobbyhadz.com/blog/react-remove-object-from-state-array[1]

作者:Borislav Hadzhiev[2]

正文从这开始~

总览

在React中,移除state数组中的对象:

  1. 使用filter()方法对数组进行迭代。
  2. 在每次迭代中,检查条件是否匹配。
  3. state设置为filter方法返回的新数组。
代码语言:javascript
复制
import {useState} from 'react';

export default function App() {
  const initialState = [
    {id: 1, name: 'Alice', country: 'Austria'},
    {id: 2, name: 'Bob', country: 'Belgium'},
  ];

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

  const removeSecond = () => {
    setEmployees(current =>
      current.filter(employee => {
        // 👇️ remove object that has id equal to 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-remove-object-from-state-array.gif

Array.filter

我们使用useState 钩子初始化employees状态变量。

我们传递给Array.filter方法的函数将在数组的每个元素中被调用。在每次迭代中,我们检查对象中的id属性是否不等于2,并返回结果。

代码语言:javascript
复制
const initialState = [
  {id: 1, name: 'Alice', country: 'Austria'},
  {id: 2, name: 'Bob', country: 'Belgium'},
];

const filtered = initialState.filter(obj => {
  // 👇️ returns truthy for all elements that
  // don't have an id equal to 2
  return obj.id !== 2;
});

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

filter方法返回一个新数组,该数组只包含回调函数返回真值的元素。

如果所有条件都不匹配,Array.filter函数将会返回空数组。

我们将函数传递到setState ,因为函数保证以当前(最新的)状态调用。

代码语言:javascript
复制
const removeSecond = () => {
  // 👇️ current is the current state array
  setEmployees(current =>
    current.filter(employee => {
      return employee.id !== 2;
    }),
  );
};

当使用前一个状态计算下一个状态时,传递一个函数给setState。否则,如果我们所访问的state数组不代表最新的值,我们可能会得到一些奇怪的Race Condition。

逻辑与

如果需要基于多个条件来移除state数组中的对象,可以使用逻辑与以及逻辑或操作符。

代码语言:javascript
复制
const initialState = [
  {id: 1, name: 'Alice', country: 'Austria'},
  {id: 2, name: 'Bob', country: 'Belgium'},
  {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;
    }),
  );
};

我们使用了逻辑与操作符,如果两边的条件都满足,将会返回真值。

逻辑或

下面是使用逻辑或操作符的例子。

代码语言:javascript
复制
const initialState = [
  {id: 1, name: 'Alice', country: 'Austria'},
  {id: 2, name: 'Bob', country: 'Belgium'},
  {id: 3, name: 'Carl', country: 'Austria'},
];

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

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

2个条件中的任何一个都必须评估为真值,才能将该元素添加到新数组中。换句话说,如果对象上的name属性等于Alice或等于Carl,该对象将被添加到新数组中。所有其他的对象都会从数组中被过滤掉。

参考资料

[1]

https://bobbyhadz.com/blog/react-remove-object-from-state-array: https://bobbyhadz.com/blog/react-remove-object-from-state-array

[2]

Borislav Hadzhiev: https://bobbyhadz.com/about

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-06-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端F2E 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 总览
  • Array.filter
  • 逻辑与
  • 逻辑或
    • 参考资料
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档