简体   繁体   中英

Is there a way to delete components from an array with a button click?

Still pretty new to react, so sorry if this question seems very simple.

I'm currently having issues where I have a component that I am attempting to add in each time the add button is clicked (which works) but when I press the delete button, it deletes all of the components in the array except the first one which cannot seem to be deleted. I am using.splice() to attempt to remove the last element in the array (-1) and setting the new state to reflect that but everything I do doesn't seem to fix anything. Any input would be greatly appreciated!

function App() {
  const [inputList, setInputList] = useState([]);
  const [disabled, setDisabled] = useState(false);

  const onAddBtnClick = event => {
    if (inputList.length < 5){
      setInputList(inputList.concat(<Autocomplete items={universities} />));
    }else{
      setDisabled(true);
    }
  };

  const onDeleteBtnClick = event => {
    setInputList(inputList.splice(-1, 1));
    if (inputList.length < 5){
      setDisabled(false);
    }
  };

  return (
    <Fragment>
      <div className="autocompleter">
        <Button onClick={onAddBtnClick} disabled={disabled} size="lg" block>Add Education (Maximum 5)</Button> 
        <Button onClick={onDeleteBtnClick} size="lg" block>Delete Education</Button> 
        {inputList}
      </div>
    </Fragment>
  );
}

If you want to delete the last element use Array.splice(0,array.length-1). This will remove your last element. Hope this helps. In your case use this block of code.

setInputList(prev=>prev.splice(0,prev.length-1));

Your problem is that splice doesn't return a new object, it returns the deleted elements. So you are setting the wrong new state.

Take a look here , you could use slice instead

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