简体   繁体   English

有没有办法通过单击按钮从数组中删除组件?

[英]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.我正在使用 .splice() 尝试删除数组中的最后一个元素 (-1) 并设置新的 state 以反映这一点,但我所做的一切似乎都没有解决任何问题。 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).如果要删除最后一个元素,请使用 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.您的问题是 splice 不会返回新的 object,它会返回已删除的元素。 So you are setting the wrong new state.所以你设置了错误的新 state。

Take a look here , you could use slice instead看看这里,你可以用slice代替

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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