Home > Blockchain >  I cant delete list from react function component
I cant delete list from react function component

Time:11-06

I am practicing react now and I face a problem in react function component with useState. And I can't delete one from the list by clicking the paragraph. Please tell me how should I do. I have no problems with setState but I wanna try this with functional components

import './style.css';
import Person from './Person/Person';

const App = (props) => {
  const [personArray, setPersonArray] = useState({
    person: [
      { name: 'mg mg', age: 20 },
      { name: 'justin', age: 17 },
      { name: 'helen', age: 12 },
    ],
    showPerson: false,
  });

  const showNameHandler = () => {
    const doesShow = personArray.showPerson;
    setPersonArray({
      person: [
        { name: 'mg mg', age: 20 },
        { name: 'justin', age: 17 },
        { name: 'helen', age: 12 },
      ],
      showPerson: !doesShow,
    });
  };

  const deletPerson = (personIndex) => {
    const person = [...personArray.person];
    person.slice(personIndex, 1);
    setPersonArray({ person: person });
  };
  let persons = null;
  if (personArray.showPerson) {
    persons = (
      <div>
        {personArray.person.map((pp, index) => {
          return (
            <Person click={() => deletPerson(index)} name={pp.name} age={pp.age} />
          );
        })}
      </div>
    );
  }
  return (
    <div>
      <div className="wrapper">
        <h1>Hello React</h1>

        {persons}

        <button onClick={showNameHandler}>
          Show Name
        </button>
      </div>
    </div>
  );
};

export default App;

CodePudding user response:

You probably meant to use splice() instead of slice().

const person = [...personArray.person];
person.splice(personIndex, 1);

CodePudding user response:

Use filter instead of slice. And you should set the whole state (person and showPerson properties)

const deletPerson = (personIndex) => {
    const person = personArray.person.filter((elem, index) => {
       return personIndex !== index;
    });
    setPersonArray({ ...personArray, person });
};

https://www.w3schools.com/jsref/jsref_filter.asp

  • Related