简体   繁体   English

如何在Mobx中执行可观察的功能?

[英]How to do an observable function in Mobx?

I have store with a collection which I want to be read only. 我有一个集合,我想要只读。 I wish to do something like but I don't know if Mobx provides a way to create a reactive function. 我希望做一些类似但我不知道Mobx是否提供了一种创建反应函数的方法。

class Store{
  private _col:Mobx.Map;
  ...

  @observable public has(id){
    return _col.has(id);
  }       
}

I am on a game architecture with no-trust-the-client in mind. 我在游戏架构上考虑到了不信任客户端。 So I don't want my view to get direct access to _col . 所以我不希望我的视图直接访问_col

@observe
class MyView extends Component {
  ...
  componentWillMount(){
    this.id = this.props.params.id;
    autorun(()=>{
      this.props.store.has(this.id)
      //do something smart
    }
  }

  ...
}

What could be the alternatives? 可能有哪些替代方案?

You can just use 你可以使用

public has(id) { return _col.has(id); public has(id){return _col.has(id); } }

For observables it doesn't matter whether they are accessed directly or through several layers of indirection, MobX will track it anyways. 对于可观察对象而言,无论是直接访问还是通过多层间接访问它们都无关紧要,MobX无论如何都会跟踪它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM