How to update Array of objects in React js using state

前端 未结 3 950
爱一瞬间的悲伤
爱一瞬间的悲伤 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 22:57

    There are four significant problems in that code.

    1. You're using the same object for all entries in your array. If you want to have different objects, you have to create multiple copies of the default.

    2. You're calling setState incorrectly. Any time you're setting state based on existing state (and you're setting values based, indirectly, on this.state.values), you must use the function callback version of setState. More: State Updates May Be Asynchronous

    3. You can't directly modify the object held in this.state.values; instead, you must make a copy of the object and modify that. More: Do Not Modify State Directly

    4. default is a keyword (even though it's not currently used), you can't use it as an identifier. Let's use defaultValue instead.

    Here's one way you can address all three (see comments):

    // #4 - `default` is a keyword
    let defaultValue = {
        name: '',
        age: ''
    };
    this.state = {
        // #1 - copy default, don't use it directly
        values: [
            Object.assign({}, defaultValue),
            Object.assign({}, defaultValue)
        ] // <=== Side note - no ; here!
    }
    
    updateName (event) {
        let index = event.target.id,
        // #2 - state updates working from current state MUST use
        // the function callback version of setState
        this.setState(prevState => {
            // #3 - don't modify state directly - copy the array...
            values = prevState.values.slice();
    
            // ...and the object, doing the update
            values[index] = {...values[index], name: event.target.value};
    
            return {values};
        });
    }
    

    Note that this line in the above:

    values[index] = {...values[index], name: event.target.value};
    

    ...uses syntax from this JavaScript enhancement proposal, currently at Stage 4 (it will be in the ES2018 snapshot spec) and commonly enabled in React build environments.

提交回复
热议问题