Object.assign() is a simple solution, but (currently) the top answer is to use it - while just fine for building stateless components, it will cause problems for the OP of the desired goal of merging two state objects.
With two arguments, Object.assign() actually mutates the first object in place, affecting future instances.
Example:
Consider two possible style configurations for the box:
var styles = { box: {backgroundColor: 'yellow', height: '100px', width: '200px'}, boxA: {backgroundColor: 'blue'}, };
Therefore, we want all our blocks to have default styles, but we want to overwrite them with a different color:
// this will be yellow <div style={styles.box}></div> // this will be blue <div style={Object.assign(styles.box, styles.boxA)}></div> // this SHOULD be yellow, but it blue. <div style={styles.box}></div>
Once Object.assign() is executed, the 'styles.box' object changes forever.
The solution is to pass an empty object to Object.assign() . In doing so, you tell the method to create a new object with the objects that you pass to it. Like this:
// this will be yellow <div style={styles.box}></div> // this will be blue <div style={Object.assign({}, styles.box, styles.boxA)}></div> // a beautiful yellow <div style={styles.box}></div>
This concept of mutating objects in place is critical to React, and the proper use of Object.assign() really useful for using libraries like Redux.
Brandon Jun 07 '16 at 18:20 2016-06-07 18:20
source share