1
state = {
  blog: {
    name: 'abc',
    score: 5
  }
}


var { blog } = this.state

// you want to do blog.score = 5

1. blog = _.merge({}, blog, {
  score: 3
})


2. blog = {
    ...blog,
    score: 5
   }

3. blog = update(blog, {
     $set: {
       score: 5
     }
   }

this.setState({blog})

I don't know if there are other ways, but would there be any preference over these?

what about

state = {
  site: { 
    blog: {
      name: 'abc',
      score: 5
    }
  }
}


site = _.merge({}, site, {
  blog: {
    score: 5
  }
})


site = update(site, {
  blog: {
    $set: {
      score: 5
    }
  })


this.setState({site})
eugene
  • 36,347
  • 56
  • 224
  • 435

2 Answers2

1

already provides utility to merge previous state with new one.

let newState = React.addons.update(this.state, {
  blog: {
    score: { $set: 5}
  }
});
this.setState(newState);

More details about this addon

Abdennour TOUMI
  • 76,783
  • 33
  • 229
  • 231
0

_.merge is a plausible solution, but the recommended way would be to use https://github.com/kolodny/immutability-helper since react-addons-update has been deemed a legacy add-on.

Yangshun Tay
  • 41,572
  • 29
  • 112
  • 131