2
let a = this.state.a; 
//setted in the constructor: {number: 1}

console.log(a); 
//Prints: {number: 1}

a.number = 2;
console.log(this.state.a);
//Prints: {number: 2}

How can I prevent a to be a reference, I want to change de value of a whitout changing the value of state.a

SpaceDogCS
  • 2,808
  • 3
  • 20
  • 49

3 Answers3

2

You can create a new object based on the state object ...

let a = { ...this.state.a }; 

once you create a new object the reference will be gone..

We are using the spread operator to clone an object refer to this article..

Renzo Calla
  • 7,486
  • 2
  • 22
  • 37
1

You can use the spread operator to create a new object:

let a = { ...this.state.a };

Alternatively, you can use Object.assign:

let a = Object.assign({}, this.state.a);
Fabian Schultz
  • 18,138
  • 5
  • 49
  • 56
  • `let a = { ...this.state.a };` didn't work, but `let a = Object.assign({}, this.state.a);` works perfectly, thank you – SpaceDogCS Feb 09 '18 at 13:11
  • 1
    To make the first option work, you'll have to [install the object rest spread transform babel plugin](https://babeljs.io/docs/plugins/transform-object-rest-spread/#installation). – Fabian Schultz Feb 09 '18 at 13:13
1

Use Object.assign like let a = Object.assign({}, this.state.a, {number:2});

or Object Spread like let a = {...this.state.a};

yvoytovych
  • 871
  • 4
  • 12