Search code examples
refluxjs

shouldComponentUpdate won't receive the newest state


I use Reflux.connect methods to change component state, but I can't get the different part in shouldComponentUpdate between nextState and this.state. Actually, this.state already has the new values I was expecting to be in nextState when shouldComponentUpdate is called.

What should I need to do when I want to use shouldComponentUpdate with Reflux?

  var component = React.createClass({
     mixins: [Reflux.connect(store1, 'store1data'),
              Reflux.connect(store2, 'store2data')],

     shouldComponentUpdate: function(nextProps, nextState) {
        //Here this.state.store1data is equal to nextState.store1data
     }

Solution

  • Make sure you're not mutating the state and instead returning a new copy of it. If your store only changes the field inside the state, then the this.state pointer already points to the mutated state.

    so in your store1, instead of:

    store1Data.someKey = newValue;
    this.trigger(store1Data)
    

    try doing:

    store1Data = _.assign({}, store1Data, {someKey: newValue}); // this uses lodash, for example
    this.trigger(store1Data)
    

    That way you will get a fresh copy of store1Data every time it changes.

    Immutability is an important concept when working with states, especially in React/Flux, since it allows you to determine quickly whether a state was changed. Try making a habit of always returning a new copy when changing the state, and to never change to anything inside the state unless you clone it first.

    Immutablity in React
    ImmutableJs