setState is not merging the values

前端 未结 2 866
温柔的废话
温柔的废话 2021-01-24 23:25

I use the following code in react in order to update state. state should finally looks like this:

this.state.output = {
 \'abc\':{
     value: 10
 }         


        
相关标签:
2条回答
  • 2021-01-24 23:49

    object spread syntax is recent spec. Here is the documentation for it: using-object-spread-operator

    Below code uses Object.assign method instead :

    handleChange = (data) => {
        this.setState(prevState => ({
            output: Object.assign({}, prevState, {
            [data.id]: data
          })
        })
    )}
    
    0 讨论(0)
  • 2021-01-25 00:08

    Because you forgot to add the other property and their values, update the object like this:

    handleChange = (data) => {
        this.setState(prevState => {
            return {
                output: {
                    ...prevState.output,      // notice this
                    [data.id]: { ...data },
                },
            }
        })
    }
    

    Or simply:

    handleChange = (data) => {
        this.setState(prevState => ({
            output: {
                ...prevState.output,
                [data.id]: { ...data },
            },
        })
    )}
    
    0 讨论(0)
提交回复
热议问题