简体   繁体   中英

Deleting a particular element from an array

state = { filters: ['all'] }


this.state.filters.includes('humans') ? 
    this.state.filters.filter(val => val !== 'humans') : this.state.filters.push(dropdown)

I'm using a condition such that, when I click on a button the item('humans') gets pushed to state and when I click on the same button again I need to remove the item('humans') from the array. Push is working fine, I need help in removing it. I used filter like the above code , it does not get added again to the array but also not removing. Thanks in advance.

要从数组中删除元素,您可以执行以下操作

filters.splice(index_of_the_val, 1);

Use:

let index = this.state.filters.indexOf('humans');
if (index !== -1)
   this.state.filters.splice(index, 1);

Or you better follow this approach to avoid mutating the state in React:

let array = [...this.state.filters]; // make a separate copy of the array
let index = array.indexOf('humans')
if (index === -1) { // not in the array
   array.push('humans');
   this.setState({filters: array});
} else { // exists in the array
   array.splice(index, 1);
   this.setState({filters: array});
}

You shouldn't modify the state with the push, 'cause it might not trigger the re-rendering. You should use the setState method.

toggleFilter = filter => {
  const isIncluded = this.state.filters.includes(filter)

  const add = (filters, filter) =>
    filters.concat(filter)

  const remove = (filters, filter) =>
    filters.filter(f => f !== filter)

  this.setState(prevState => ({ 
    filters: isIncluded 
               ? remove(prevState.filters, filter)
               : add(prevState.filters, filter)
  }))
}

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