Participant variables in the reaction class are "separated" by reference

When I create multiple instances of the reaction class (using React.createElement in the same class), some member members are shared between the instances (arrays and objects are shared, strings and booleans, etc.).

To me it seems terrible, scary and wrong. Is this a mistake or is there another way to do what I want to do?

Please see: http://jsbin.com/kanayiguxu/1/edit?html,js,console,output

+4
source share
1 answer

, , , React.

, :

var MyComponent = React.createClass({
  myArray: [1, 2, 3],
  componentWillMount() {
    this.myArray.push(this.myArray.length + 1);
  },
  render() {
    return (
      <span>{this.myArray.length}</span>
    );
  }
});

:

var MyComponent = React.createClass({
  getInitialState() {
    return {
      myArray: [1, 2, 3]
    };
  },
  componentWillMount() {
    this.setState(state => {
      state.myArray.push(state.myArray.length + 1);
      return state;
    });
  },
  render() {
    return (
      <span>{this.myArray.length}</span>
    );
  }
});

, this.state this.props, React.

, , , React , , , . , React , .

, , , , React.createClass() . , myArray, , , .

- , this.state, - componentWillMount this. , , .

, , , React.createClass(), . - , React. :

var obj = {
  myArray: [1, 2, 3],
  title: 'My title',
  componentWillMount() {
    this.myArray.push(this.myArray.length + 1);
  },
  render() {
    return (
      <span>{this.myArray.length}</span>
    );
  }
}

var MyComponent = React.createClass(obj);

// This doesn't change the component, since 'obj' isn't used anymore
// by React, it has already copied all properties.
obj.title = 'New title';

// This however affects the component, because the reference to the array
// was copied to the component prototype, and any changes to what the 
// reference points to will affect everyone who has access to it.
obj.myArray.push(666);
+10

All Articles