Removing element from array in component state

前端 未结 10 2058
感动是毒
感动是毒 2020-11-28 01:31

I am trying to find the best way to remove an element from an array in the state of a component. Since I should not modify the this.state variable directly, is

10条回答
  •  没有蜡笔的小新
    2020-11-28 02:00

    You could make the code more readable with a one line helper function:

    const removeElement = (arr, i) => [...arr.slice(0, i), ...arr.slice(i+1)];
    

    then use it like so:

    this.setState(state => ({ places: removeElement(state.places, index) }));
    

提交回复
热议问题