亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

一個mobx中computed屬性的問題

一個mobx中computed屬性的問題

一只名叫tom的貓 2018-12-11 11:22:51
對于單個對象,我可以使用computed通過計算獲得一些屬性,比如@observable good = {    number: 2,    price: 3}@computed get totalPrice() {    return this.good.number * this.good.price;}對于數組,比如@observable goodsList = [{    number: 2,    price: 3},{    number: 2,    price: 3}]這種情況我如何通過computed獲得數組某個元素的計算屬性呢,還是只能在改變number的函數中手動去更改,但是我數組的對象中并沒有一個totalPrice的屬性,每次把單個good push到goodsList中去還要給good添加一個totalPrice屬性豈不是很麻煩
查看完整描述

1 回答

?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

把good弄成一個單獨的model文件


export default class Good{

  @observable number;

  @observable price;

  constructor(number, price) {

    this.number = number;

    this.price = price;

  }

  

  @computed

  get totalPrice() {

    return this.number * this.price

  }   


}

然后在goodList文件中


  @action

  addGood(...args) {

    this.todos.push(new Good(...args));

  }

這樣就實現了自動計算, 訪問的時候類似 this.props.goodList[0].totalPrice


參考這個TODO LIST


查看完整回答
反對 回復 2019-01-11
  • 1 回答
  • 0 關注
  • 1150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號