简体   繁体   中英

react js state variable updates automatically without setstate method

I am working on a react js project. I have a state variable and I initialize that state variable ( x_state ) with another normal variable ( x ) during the componentDidMount() method. But whenever my normal variable ( x ) gets updated it is automatically updating the state variable ( x_state ).

export class Demo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      x_state: null
    }
    this.x = {}
  }

  componentDidMount() {
    this.setState({
      x_state: this.x
    })
  }
}

The local variable this.x is updating on specific conditions inside the code. whenever the local variable this.x is updating it is automatically updating the state variable x_state. How to prevent the automatic update or automatic setstate method invoking

This is because x is an object and you are setting the reference by this code

this.setState({
   x_state: this.x
})

You should make a copy of it using Object.assign()

this.setState({
      x_state: Ojbect.assign({},this.x)
})

Or if this.x is a nested object initially you can use JSON.parse(JSON.stringify())

this.setState({
     x_state: JSON.parse(JSON.stringify(this.x))
})

@Maheer Ali & @adiga are correct. Since the state variable x_state and the local variable this.x point to the same object in memory, they both update in conjunction.

You may also use the Spread Operator to copy the properties of the local object to the state variable.

this.setState({
   x_state: { ...this.x }
})

ECMAScript 6 defines seven data types: Six data types that are primitives : Boolean, Null, Undefined, Number, String, Symbol and Object .

Primitive Data Types are passed By Value and Objects are passed By Reference.

So when you think you're "assigning" the value of an obj1 = obj2 you're actually creating a reference in ( obj1 ) 'pointing' towards ( obj2 ), so any changes in ( obj2 ) will automatically be made in ( obj1 ). You could use any of the answers above or use a spread operator, any method that returns a shallow copy of the object you want to copy. Here is an intersting post on the topic .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM