• mobx(v5 -> v6)


    前言: 好久不用mobx了,今天正好搞了个新架子,安装了最新的mobx, 按照以前的写法, 居然不生效!!!

    最终查阅文档发现: mobx版本6 更新了写法

    版本5代码示例:

     1 import { observable, action } from 'mobx'
     2 
     3 export default class UserStore {
     4   @observable token: string = localStorage.getItem('token') || ''
     5   @observable userInfo: any = null
     6 
     7   @action
     8   setUserInfo = (val: any) => {
     9     this.userInfo = val
    10   }
    11 
    12   @action
    13   setToken = (val: string) => {
    14     this.token = val
    15     localStorage.setItem('token', val)
    16   }
    17 
    18 }

    版本6写法:(官方推荐第一种)

     1 // 第一种
      import { makeObservable, observable, action } from 'mobx'; 2 3 export default class UserStore { 4 token: string = localStorage.getItem('token') || ''; 5 userInfo: any = null; 6 constructor() { 7 makeObservable(this, { 8 token: observable, 9 userInfo: observable, 10 setUserInfo: action, 11 setToken: action, 12 }); 13 } 14 setUserInfo = (val: any) => { 15 this.userInfo = val; 16 }; 17 18 setToken = (val: string) => { 19 this.token = val; 20 localStorage.setItem('token', val); 21 }; 22 }

    或者直接使用makeAutoObservable 默认推断所有属性, 不用单个一一声明

     1 // 第二种
      import { makeAutoObservable } from 'mobx'; 2 3 export default class UserStore { 4 token: string = localStorage.getItem('token') || ''; 5 userInfo: any = null; 6 7 constructor() { 8 makeAutoObservable(this); 9 } 10 11 setUserInfo = (val: any) => { 12 this.userInfo = val; 13 }; 14 15 setToken = (val: string) => { 16 this.token = val; 17 localStorage.setItem('token', val); 18 }; 19 20 }

     话说回来, mobx 为什么要进行这么大的改动呢?

    文档中有这段话, 

    翻译过来就是:

    版本 6 之前的 MobX 鼓励使用 ES.next 装饰器将事物标记为可观察的、计算的和动作的。

    但是,装饰器目前还不是 ES 标准,标准化的过程需要很长时间。

    看起来标准也将与之前实现装饰器的方式不同。

    出于兼容性考虑,我们选择在 MobX 6 中放弃它们,并推荐使用 makeObservable / makeAutoObservable 代替

      

    Every day deserves to be expected
  • 相关阅读:
    ACM: POJ 1401 Factorial-数论专题-水题
    ACM:POJ 2739 Sum of Consecutive Prime Numbers-素数打表-尺取法
    ACM: HDU 1028 Ignatius and the Princess III-DP
    ACM: HDU 2563 统计问题-DFS+打表
    ACM: How many integers can you find-数论专题-容斥原理的简单应用+GCD
    ACM: Happy 2004-数论专题-因子求和-快速幂
    ACM:a^b%p-数论-快速幂-快速乘
    ACM: 强化训练-Beautiful People-最长递增子序列变形-DP
    POJ 1472 Instant Complexity 应该叫它编程题。。
    POJ 3393 Lucky and Good Months by Gregorian Calendar 模拟题
  • 原文地址:https://www.cnblogs.com/aloehui/p/14863609.html
Copyright © 2020-2023  润新知