• [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

  • 相关阅读:
    50个SQL语句(MySQL版) 问题六
    50个SQL语句(MySQL版) 问题五
    50个SQL语句(MySQL版) 问题四
    50个SQL语句(MySQL版) 问题三
    50个SQL语句(MySQL版) 问题二
    50个SQL语句(MySQL版) 问题一
    50个SQL语句(MySQL版) 建表 插入数据
    相邻元素margin的自动合并与float的坑
    STL之list
    你真的会用搜索吗?—— google 搜索技巧
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6071447.html
Copyright © 2020-2023  润新知