zoukankan      html  css  js  c++  java
  • [MobX] MobX fundamentals: deriving computed values and managing side effects with reactions

    Derivations form the backbone of MobX and come in two flavors: computed values are values that can be derived from the state automatically. And reactions can be used to manage side effects, such as drawing the user interface. In this lesson you will learn how these concepts relate to each other and how they are optimized automatically by MobX.

    const {observable, computed} = mobx;
    const {observer} = mobxReact;
    const {Component} = React;
    const DevTools = mobxDevtools.default;
    
    const t = new class Temperature {
      @observable unit = "C";
      @observable temperatureCelsius = 25;
    
      @computed get temperatureKelvin() {
        console.log("calculating Kelvin")
        return this.temperatureCelsius * (9/5) + 32
      }
       
      @computed get temperatureFahrenheit() {
        console.log("calculating Fahrenheit")
        return this.temperatureCelsius + 273.15
      }
       
      @computed get temperature() {
        console.log("calculating temperature")
        switch(this.unit) {
          case "K": return this.temperatureKelvin + "ºK"
          case "F": return this.temperatureFahrenheit + "ºF"
          case "C": return this.temperatureCelsius + "ºC"
        }
      }
    }
       
    const App = observer(({ temperature }) => (
      <div>
        {temperature.temperature}
        <DevTools />
      </div>
    ))
    
    ReactDOM.render(
      <App temperature={t} />,
      document.getElementById("app")
    )

     If 'unit' or 'temperateureCelsius' changed, it will automaticlly trigger the corresponding @computed function to run based on current state

    JS Bin on jsbin.com

  • 相关阅读:
    接口和抽象类
    TSQL向自增字段中插入值
    字符串驻留备忘
    SQL Like中的逗号分隔符
    TSQL的一点小备忘
    ADO.NET与ADO
    JavaScript Office文档在线编辑备忘
    位运算练习:求多数的大数、二进制数中1的个数
    Vimeo反反复复地重生死亡。
    海底浓烟,低分辨率测试。
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6071447.html
Copyright © 2011-2022 走看看