Whats the best way to update an object in an array in ReactJS?

前端 未结 4 1244
悲&欢浪女
悲&欢浪女 2020-11-22 10:56

If you have an array as part of your state, and that array contains objects, whats an easy way to update the state with a change to one of those objects?

Example, mo

4条回答
  •  一生所求
    2020-11-22 11:03

    Trying to clean up/ explain better how to do this AND what's going on.

    • First, find the index of the element you're replacing in the state array.
    • Second, update the element at that index
    • Third, call setState with the new collection
    import update from 'immutability-helper';
    
    // this.state = { employees: [{id: 1, name: 'Obama'}, {id: 2, name: 'Trump'}] } 
    
    updateEmployee(employee) {
        const index = this.state.employees.findIndex((emp) => emp.id === employee.id);
        const updatedEmployees = update(this.state.employees, {$splice: [[index, 1, employee]]});  // array.splice(start, deleteCount, item1)
        this.setState({employees: updatedEmployees});
    }
    

    Edit: there's a much better way to do this w/o a 3rd party library

        const index = this.state.employees.findIndex(emp => emp.id === employee.id),
              employees = [...this.state.employees] // important to create a copy, otherwise you'll modify state outside of setState call
        employees[index] = employee;
        this.setState({employees});
    

提交回复
热议问题