乐趣区

关于mobx:汇总mobx奇淫技巧

简化 action 属性更新

通常状况下,store中会有很多属性,其中有些属性更新会很频繁,每一个属性都须要写一个 action 函数去更新,当这种须要变更的属性越多时,会导致 store 中代码量异样的宏大,可读性也会升高。就如上面代码一样:

class TestStore {@observable info = {} as IInfo;
  
  @observable list = [] as IList;
  
  @action
  setInfo = (value: IInfo) => {this.info = value;}
  
  @action
  setList = (value: IList) => {this.list = value;}
}

引入 typescriptkeyof关键字应用,能够将上述 action 函数简化如下:

class TestStore {@observable info = {} as IInfo;
  
  @observable list = [] as IList;
  
  @action
  setValue = <T extends keyof TestStore>(key: T, value: this[T]) => {this[key] = value;
  }
}
退出移动版