zahabba zahabba - 1 year ago 63
React JSX Question

Why is an imported value being mutated?

I'm not understanding why, in a file where I define a React class, a variable assigned to an import and one that is never mutated still changes.

import statuses from '../statuses'; // array of 6 items

class MyComponent extends React.Component {

constructor(props) {
super(props);
this.statuses = statuses;
}

render() {
const statusOptions = this.statuses;
if (statuses.length === statusOptions.length) statusOptions.push(obj);
console.log(statuses.length); // 7 (?!?!)
}
}


I have no idea why
statuses
would be updated at all, and why it would get mutated as if it were
statusOptions
here. (To be clear, I also logged
statuses
itself, and sure enough,
obj
had been pushed to the array.

Answer Source

statuses, this.statuses and statusOptions are all references to the same object.

Push to one, and it'll appear in all three.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download