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

  • 相关阅读:
    openssl用法详解
    单例模式
    __new__静态方法
    django自带加密模块的使用
    celery 框架
    理解RESTful架构
    [Swoole] 在Ubuntu下安装、快速开始
    [Javascript] 动态隐藏和显示 Layui 数据表格的列
    [PHP] CURL获取cookie,模拟登录获取数据
    [Python] 命令行模式阅读博客园的博文
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6071447.html
Copyright © 2011-2022 走看看