[英]how this specific code removes item from list
I'm trying to learn to react online and I understood everything except this line code我正在尝试学习在线做出反应,除了这行代码,我什么都懂
const removeItem = (id) => {
let newPeople = people.filter((person) => person.id !== id);
setPeople(newPeople);
};
especially how person.id !== id
removes the item from list and add to new list特别是
person.id !== id
如何从列表中删除项目并添加到新列表
here is the full code这是完整的代码
import React from 'react';
import { data } from '../../../data';
const UseStateArray = () => {
const [people, setPeople] = React.useState(data);
const removeItem = (id) => {
let newPeople = people.filter((person) => person.id !== id);
setPeople(newPeople);
};
return (
<>
{people.map((person) => {
const { id, name } = person;
return (
<div key={id} className='item'>
<h4>{name}</h4>
<button onClick={() => removeItem(id)}>remove</button>
</div>
);
})}
<button className='btn' onClick={() => setPeople([])}>
clear items
</button>
</>
);
};
export default UseStateArray;
first you shold khow how filter works,首先你要知道过滤器是如何工作的,
The filter() method creates a new array filled with elements that pass a test provided by a function. filter() 方法创建一个新数组,其中填充了通过 function 提供的测试的元素。
in your case test is person.id !== id
, if test passed for an element that element will be in new array.在您的案例中,测试是
person.id !== id
,如果测试通过了某个元素,则该元素将位于新数组中。 otherwise element will not be in new array.否则元素不会在新数组中。 is it clear?
清楚吗?
The filter method creates a shallow copy of an array but not the whole array but only those elements that fulfills the predicate. filter 方法创建一个数组的 浅表副本,但不是整个数组,而是只创建满足谓词的那些元素。
So newPeople
will contain a copy of all the elements within people
that it's people[element].id
is different than id
.所以
newPeople
将包含people
中所有元素的副本,它是people[element].id
不同于id
。
Visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for additional details of filter method.访问https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter了解过滤器方法的更多细节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.