Immutable.js & react.js setState clears object prototype

I have the following code in a component:

constructor() {
    this.state = Immutable.fromJS({
            user : {
                wasChanged : false,
                firstName : false,
                lastName : false,
                address : {
                    street : false,
                }
            }
        });
}
onEdit({target: {dataset: {target}}}, value) {
      this.setState(function (prevState) {
          return prevState.setIn(['user', target], value);
        });
  }
render() {
    var user = this.state.get('user').toJS();
    ...
}

The problem is that when I try to update the value in onEdit, I see that prevState has a different set of prototypes. I don’t understand why and what I am doing wrong. I see it in the console

> Object.getPrototypeOf(this.state)
src_Map__Map {@@__IMMUTABLE_MAP__@@: true}

> Object.getPrototypeOf(prevState)
Object {}

After the state has been changed, it proceeds to rendering, where of course he cannot find the get function or anything from Immutable

Using the reaction with add-ons 0.13.3.

+4
source share
2 answers

Put it as a key in a state.

this.state = {
  data: Immutable...
};

Currently, the reason you cannot use the Immutable object as a state, for the same reason you cannot do it this.state = 7: it's not a simple JavaScript object.

:

React.Component.prototype.setState = (changes) => {
  batchUpdate(() => {
    // copies own properties from state to the new object
    // and then own properties from changes to the new object
    var nextState = Object.assign({}, state, changes);

    this.componentWillUpdate(...);
    this.state = nextState;
    queueDomUpdateStuff(this.render(), () => this.componentDidUpdate());
  });
};
+6

state JavaScript-; . 3303.

+2

Source: https://habr.com/ru/post/1598471/


All Articles