Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

reactjs - React Array State Filter Clears the Array

When i press the delete button, i want to update the itemListState in my App.js. But it deletes everything in the state. What is wrong in my "itemDeleteHandler" function? Index number and the id matches. Filter function should do the work.

import React, { useState } from 'react';
import './App.css';
import UserInput from './components/UserInput';
import ItemList from './components/ItemList';

const App = (props) => {
  const [itemListState, setItemListState] = useState([]);

  const userInputHandler = (newUserInput) => {
    setItemListState((prevState) => ([
      ...prevState, newUserInput
    ]))
  }

  const itemDeleteHandler = (id) => {
    setItemListState((prevState) => ([
      prevState.filter((item, index) => {
        // DELETES ALL THE ITEMS WHY?
        return parseInt(id) !== index;
      })
    ]));
    console.log(itemListState);
  }

  return (
    <div>
      <UserInput onAddUserInput={userInputHandler} />
      <hr className="item__hr" />
      <ItemList userInputProp={itemListState} onDeleteItem={itemDeleteHandler} />

    </div>
  );
}

export default App;
question from:https://stackoverflow.com/questions/65646322/react-array-state-filter-clears-the-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have an extraneous pair of brackets in the delete handler, so you end up with a list with 1 item containing the rest.

You'll want

const itemDeleteHandler = (id) => {
  setItemListState((prevState) =>
    prevState.filter(
      (item, index) =>
        parseInt(id) !== index,
    ),
  );
};

instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...