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
  • 39,839
  • 68
  • 255
  • 489

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
  • 87,526
  • 38
  • 249
  • 254
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
  • 49,270
  • 33
  • 114
  • 141