reactjs - How to have different react components share and acknowledge each other's states? -
i've encountering dynamic components not being able update each other directly. multiple models update each other's attributes not views.
model2view.onclick=() { model1.change; model1view.forceupdate(); }
i've resorted throwing in callback functions mix wrapper updates model , forceupdate overhead view after change.
it gets worse when model update modelside function updates more 1 model, in case i've been using nearest ancester view perform forceupdate.
model2view.onclick=() { following 3 wrapped in 1 method on model1 model1.change; model2.change; model3.change; modelswrapperview.forceupdate(); }
after many force updates, wondering if that's way react meant used or i'm missing something.
here's oversimplified example of problem i'm trying solve:
you attempting mutate object part of state , react won't re-render because doesn't know has changed. that's why you're having call forceupdate
.
you should treat state immutable , use setstate
update (updated demo):
class transformersapp extends react.component { toggledeception() { // create new object rather mutating existing one. var newtransformer = object.assign({}, this.state.transformer, { isdecepticon: !this.state.transformer.isdecepticon }); // update state. this.setstate({ transformer: newtransformer }); } }
this made clear docs setstate
:
never mutate
this.state
directly, callingsetstate()
afterwards may replace mutation made. treatthis.state
if immutable.
you may find helpful use immutable.map
state object prevent mutating state @ all.
Comments
Post a Comment