user2167582 February 2016

How to have different react components share and acknowledge each other's states?

I've frequently encountering dynamic components not being able to update each other directly. Multiple models that update each other's attributes but not their views.

model2View.onClick=() {
  model1.change;
  model1View.forceUpdate();
}

i've often resorted to throwing in callback functions into the mix which is just a wrapper that updates the model and forceupdate the overhead view after change.

it gets worse when the model update is a modelside function that updates more than one model, in which case I've been using the nearest ancester view to perform the forceupdate.

model2View.onClick=() {
   the following 3 could be wrapped in one method on model1
  model1.change;
  model2.change;
  model3.change;

  modelsWrapperView.forceUpdate();
}

After many force updates, I am just wondering if that's the way react was meant to be used or I'm missing something.

Here's an oversimplified example of the problem i'm trying to solve:

https://jsfiddle.net/x3azn/ann6qb30/1/

Answers


James Allardice February 2016

You are attempting to mutate an object that is part of your state and React won't re-render because it doesn't know that something has changed. That's why you're having to call forceUpdate.

You should treat state as immutable and use setState to update it (updated demo):

class TransformersApp extends React.Component {
  toggleDeception() {

    // Create a new object rather than mutating the existing one.
    var newTransformer = Object.assign({}, this.state.transformer, {
      isDecepticon: !this.state.transformer.isDecepticon
    });

    // Update the state.
    this.setState({
      transformer: newTransformer
    });
  }
}

This is made clear by the docs for setState:

NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

You may find it helpful to use something like Immutable.Map as your state object as that will prevent you from mutating the state at all.

Post Status

Asked in February 2016
Viewed 2,888 times
Voted 10
Answered 1 times

Search




Leave an answer