How to update Array of objects in React js using state

前端 未结 3 946
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-25 22:16

I want to update value of one object only but updating value of one Object, Updates the value for all objects.

let default = {
    name: \'\',
    age: \'\'
}
th         


        
3条回答
  •  时光说笑
    2021-01-25 23:10

    I would use the Array.prototype.map function with combination of the object spread syntax (stage 4):

    Note that i changed the name of the default object to obj.
    default is a reserved key word in javascript

    let obj = {
        name: '',
        age: ''
    }
    this.state = {
        values: Array(2).fill(obj)
    }
    
    updateName(event){
        const {id, value} = event.target;  
        this.setState(prev => {
        const {values} = prev;
    
        const nextState = values.map((o,idx) => {
            if(idx !== id)
            return o; // not our object, return as is
    
          return{
              ...o,
              name: value;
            }
        });
    
          return{
            values: nextState
          }
        });
    }
    

提交回复
热议问题