reactjs - How to make simple mobx reaction work in sub component -
i miss in mobx observables , reactions. prepared 2 examples, 1 of them works, other not, don't understand why.
example 1 (does not work):
@observer class alert1 extends component { constructor(props) { super(props); this.r2 = reaction( () => this.props.v1, v => console.log("alert1 reaction trigger",v) ); } render() { return null; } } @observer class main extends component { @observable v1 = false; render() { return ( <div> <alert1 v1={this.v1} /> <button onclick={e=>this.v1=!this.v1}>switch</button> </div> ); } }
in example 1 send observable variable in props , create reaction in alert1 component, not trigger.
example 2 (works):
@observer class alert2 extends component { constructor(props) { super(props); this.r2 = reaction( () => this.props.someobj.v1, v => console.log("alert2 reaction trigger",v) ); } render() { return null; } } @observer class main extends component { constructor(props) { this.someobj = observable({v1:observable(false)}); } render() { return ( <div> <alert2 someobj={this.someobj} /> <button onclick={e=>this.someobj.v1=!this.someobj.v1}>switch</button> </div> ); } }
that's same example 1, wrap v1 observable other observable. alert2 reaction works.
the same time if move reactions alert1 , alert2 components main component's constructor, both reactions works.
here's jsfiddle example both components, https://jsfiddle.net/kasheftin/zex0qjvf/1/
see https://mobxjs.github.io/mobx/best/react.html, in first example, not passing observable around, plain boolean value (true
or false
), there nothing reaction react to. in javascript, values immutable per definition observable. properties observable.
in second example pass object observable property, can reacted to.
note creating boxed observable work, can passed around first class citizens. e.g.: v1 = observable(false)
, reaction(() => this.props.v1.get(), ...
Comments
Post a Comment