简体   繁体   中英

How to setState to update an array in React?

I need to update an array in the state of my component in React. I've seens several topic with this question, but so far all of them are adding new items to the array with the spread operator, but I need to add OR remove items on a callback like this:

  handleCheck (newStatus, isChecked) {
    this.setState({ filterStatus: [...this.state.filterStatus, newStatus] })
  }

But the problem here is that it didn't work for status where the isChecked boolean comes false to remove them from the array

What is the best way to add or remove items from that array, hopefully with spread operator?

Thanks

try to use the .filter to remove the element. Remember to duplicate the array (using [...array] syntax) before using .filter, to don't change the original array:

handleCheck (newStatus, isChecked) {
    let newArray = isChecked? // if isChecked is true
        [...this.state.filterStatus, newStatus] : // add element
        [...this.state.filterStatus].filter(e => e !== newStatus); // remove the elements that are equal to newStatus
    this.setState({ filterStatus: newArray})
}

Put the check, add the element only when the bool isChecked is true, otherwise use filter to remove the element from the array.

Like this:

handleCheck (newStatus, isChecked) {
    this.setState(prevState => { 
        let filterStatus;
        if (isChecked) {
            filterStatus = [...prevState.filterStatus, newStatus];
        } else {
            filterStatus = prevState.filterStatus.filter(el => el.id !== newStatus.id)
        }
        return { filterStatus }
    })
}

Note: In place of id in filter callback method use the correct unique property name.

Think it functionnal !

const prevArray = this.state.array;
const itemsToAdd = [item, item, item];

//this function map the prev array escaping elements to remove 
//and then push itemsToAdd to the new array
const updateArray = ( i = [0], newArray = [] ) => 
  i < prevArray ? 
    yourRemovingCondition(prevArray[i]) ? 
      updateArray( i + 1, newArray ) 
    : updateArray( i + 1, [...newArray, prevArray[i])
  : [...newArray, ...itemsToAdd]
;

setState({array: updateArray()];

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