Removing element from array in component state

前端 未结 10 2056
感动是毒
感动是毒 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

    As mentioned in a comment to ephrion's answer above, filter() can be slow, especially with large arrays, as it loops to look for an index that appears to have been determined already. This is a clean, but inefficient solution.

    As an alternative one can simply 'slice' out the desired element and concatenate the fragments.

    var dummyArray = [];    
    this.setState({data: dummyArray.concat(this.state.data.slice(0, index), this.state.data.slice(index))})
    

    Hope this helps!

提交回复
热议问题