首页 > 解决方案 > React Mobx - 从其他商店更改商店而不渲染观察者组件

问题描述

我必须在一家商店@observable按功能更新变量。@action当我@actioncomponent类中调用它时,它会更改@observable变量并重新渲染@observer组件。但是当我尝试@action其他商店@action调用它时,通过使用回调,变量被更改但组件不会重新渲染。@observable@observer

一店:


class OneStore {
   @observable variable;

   @action
   setVariable(value) {
      this.variable = value;
   }
}

其他店铺:

class OtherStore {

   @action
   setVariable(callBack, value) {
      callBack(value); //callBack is oneStore.setVariable
   }
}

@observer零件:

@inject('oneStore')
@observer
class ObserverComponent extends Component {

   render() {
      if (this.props.oneStore.variable) {
         return (
            <div> {this.props.oneStore.variable} <div/>
         );
      } else { return null; }
   }
}

我也尝试通过@computedget 函数获取变量,它仍然没有重新渲染。

标签: reactjsmobxmobx-react

解决方案


我试图为动作添加绑定 -@action.bound它很简单......

我认为thisOneStore 在嵌套回调后被破坏了。

正确的代码是:

class OneStore {
   @observable variable;

   @action.bound
   setVariable(value) {
      this.variable = value;
   }
}

推荐阅读