remove an object the state array in react-ag捕鱼王app官网

current location:home > learning > web front-end > react >

remove an object the state array in react

author:jiyik last updated:2025/03/10 views:

to remove an object from the state array in react:

  1. use filter()the method to iterate over an array.
  2. in each iteration, check whether the condition is met.
  3. sets state to filterthe new array returned by the method.
import {usestate} from 'react';
export default functionapp() {
  const initialstate = [
    {id: 1, name: '迹忆客', site: 'www.jiyik.com'},
    {id: 2, name: '百度', site: 'www.baidu.com'},
  ];
  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><buttononclick={removesecond}>remove secondbutton>
      {employees.map(({id, name, country}) => {
        return (
          <divkey={id}><h2>name: {name}h2><h2>country: {site}h2><hr />div>
        );
      })}
    div>
  );
}

deleting an object from the state array in react

we use usestatethe hook to initialize an employee state variable.

the function we pass to array.filterthe method will be called for each element in the array.

in each iteration, we check if the object's id property is not equal to 2 and return the result.

const initialstate = [
    {id: 1, name: '迹忆客', site: 'www.jiyik.com'},
    {id: 2, name: '百度', site: 'www.baidu.com'},
];
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: '迹忆客', site: 'www.jiyik.com'}]
console.log(filtered);

filterthe method returns a new array containing only those elements for which the callback function returns a true value.

if the condition is never met, array.filterthe function returns an empty array.

we setstatepass a function to , because that function is guaranteed to be called with the current (latest) state.

const removesecond = () => {
  // 👇️ current is the current state array
  setemployees(current =>
    current.filter(employee => {
      return employee.id !== 2;
    }),
  );
};

a function is passed to when calculating the next state using the previous state setstate.

otherwise, we could run into some weird race conditions if the state array we have access to doesn't represent the latest values.

if we need to remove objects from the state array based on multiple conditions, use logical and &&or logical or ||operators.

const initialstate = [
  {id: 1, name: '迹忆客', site: 'www.jiyik.com'},
  {id: 2, name: '百度', site: 'www.baidu.com'},
  {id: 3, name: 'google', site: 'www.google.com'},
];
const [employees, setemployees] = usestate(initialstate);
const remove = () => {
  setemployees(current =>
    current.filter(employee => {
      return employee.id !== 3 && employee.id !== 2;
    }),
  );
};

we have used the logical and &&operator, which will only return a true value if both conditions are met.

the callback function returns true only if the object's id property is not equal to 3 and not equal to 2 .

here is an ||example using the logical or operator.

const initialstate = [
  {id: 1, name: '迹忆客', site: 'www.jiyik.com'},
  {id: 2, name: '百度', site: 'www.baidu.com'},
  {id: 3, name: 'google', site: 'www.google.com'},
];
const [employees, setemployees] = usestate(initialstate);
const remove = () => {
  setemployees(current =>
    current.filter(employee => {
      return employee.name === 'alice' || employee.name === 'carl';
    }),
  );
};

either of the two conditions must evaluate to a truthy value for the element to be added to the new array.

in other words, if the name property of an object is equal to迹忆客or equal to百度, then the object will be added to the new array. all other objects are filtered out of the array.

for reprinting, please send an email to 1244347461@qq.com for approval. after obtaining the author's consent, kindly include the source as a link.

article url:

related articles

how to create a slee p function in react.js

publish date:2025/03/09 views:191 category:react

在 react 中创建 sleep 函数:定义一个以毫秒数为参数的函数。该函数应返回一个 promise,该 promise 在提供的毫秒数后得到解决。

how to handle visibility: hidden in react

publish date:2025/03/09 views:62 category:react

在 react 中将 css visibility 属性设置为 hidden:在指示元素是否应该可见的状态中存储一个布尔值。有条件地在元素的样式属性中设置可见性属性。例如,style={{visibility: isvisible ? “visible”

update state when props change in react

publish date:2025/03/09 views:157 category:react

要在 react 中的 props 更改时更新状态:将 props 作为依赖项传递给 useeffect 钩子。每次 props 改变时,useeffect 中的逻辑都会重新运行。

publish date:2025/03/09 views:70 category:react

在 react 中更新对象状态数组:使用 map() 方法遍历数组。在每次迭代中,检查是否满足某个条件。更新符合条件的对象的属性。

publish date:2025/03/09 views:146 category:react

要解决 react 中的“uncaught referenceerror: process is not defined”,需要在项目的根目录中打开终端并通过运行 npm install react-scripts@latest 更新 react-scripts 包的版本,并在必要时重新安装依赖项

publish date:2025/03/09 views:81 category:react

在 react 中有条件地将 css `display` 属性设置为 none:在指示是否应显示元素的状态中存储一个布尔值。有条件地在元素的 `style` 属性中设置 display 属性。例如,style={{display: isshown ? 'block'

publish date:2025/03/09 views:184 category:react

在 react 中使用模板文字进行字符串插值,例如 div classname={text-white ${myclass}} 。 模板文字用反引号分隔,并允许我们使用美元符号和大括号 ${expression} 语法嵌入变量和表达式。 import ./

publish date:2025/03/09 views:106 category:react

在 react 中使用方括号获取数组的第一个元素,例如 const first = arr[0]; . 索引为 0 的数组元素是数组中的第一个元素。 如果数组为空,则返回 undefined 值。 import {usestate} from react ; const ap

publish date:2025/03/08 views:88 category:react

在 react 中获取鼠标位置:在元素上设置 `onmousemove` 属性或在窗口对象上添加事件侦听器。提供事件处理函数。访问事件对象的相关属性。

scan to read all tech tutorials

social media
  • https://www.github.com/onmpw
  • qq:1244347461

recommended

tags

scan the code
easier access tutorial
网站地图