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
Answer
@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 }
})
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM