跳到主要内容

计算属性

单个 Entity 的计算​

Entity 类就是普通的类,因此任何常见的派生数据都可以直接作为 getter 添加到类本身上。

import { All, Entity, Query } from '@data-client/rest';

class User extends Entity {
id = '';
firstName = '';
lastName = '';
username = '';
email = '';

get fullName() {
return `${this.firstName} ${this.lastName}`;
}

static key = 'User';
}

如果计算开销较大,可以随意加上一些记忆化。

import { All, Entity, Query } from '@data-client/rest';
import memoize from 'nano-memoize';

class User extends Entity {
truelyExpensiveValue = memoize(() => {
// compute that expensive thing!
});
}
提示

如果你只是想把某个字段反序列化为更有用的形式,例如 Temporal.Instant 或 BigNumber,可以使用声明式的 static schema。

import { All, Entity, Query } from '@data-client/rest';
import BigNumber from 'bignumber.js';

class User extends Entity {
id = '';
firstName = '';
lastName = '';
createdAt = Temporal.Instant.fromEpochMilliseconds(0);
lifetimeBlinkCount = BigNumber(0);

static key = 'User';

static schema = {
createdAt: Temporal.Instant.from,
lifetimeBlinkCount: BigNumber,
};
}

全局计算​

Query 可以从多个 Entity 派生数据,比如购物车的总计。这称为聚合。在你的 resource 旁定义一次,然后就能在任何地方用 useQuery() 读取它。

import { Query } from '@data-client/rest';
import { CartResource } from './resources/Cart';

export const freeShippingAt = 50;

export const getCartTotals = new Query(CartResource.getList.schema, items => {
  const count = items.reduce((sum, item) => sum + item.quantity, 0);
  const subtotal = items.reduce((sum, item) => sum + item.total, 0);
  const toFreeShipping = Math.max(0, freeShippingAt - subtotal);
  const shipping = subtotal && toFreeShipping ? 5 : 0;
  return {
    count,
    subtotal,
    shipping,
    total: subtotal + shipping,
    toFreeShipping,
  };
});
实时预览

这里的购物车徽标、免运费进度条、订单摘要和结账按钮都读取 getCartTotals。无论有多少组件读取它,每次变化它只运行一次,并且在它读取的 CartItem 或 Product 发生变化之前都返回同一个对象。因此即使在乐观更新进行中,每个视图也保持一致。

不要在组件中计算聚合,否则每份副本都可能出现偏差。应当把它们放进 Query 中。