zahabba zahabba - 1 year ago 72
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) {
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
would be updated at all, and why it would get mutated as if it were
here. (To be clear, I also logged
itself, and sure enough,
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