简体   繁体   中英

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

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.

in your case test is person.id !== id , if test passed for an element that element will be in new array. 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.

So newPeople will contain a copy of all the elements within people that it's people[element].id is different than id .

Visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for additional details of filter method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM