当项目可以存在于不同的模块中时,如何存储项的列表?
to items还是Multi to items?我假设会有很多不同的模块来存储项目,这些模块越多,我就越想离开一个状态。
一州
class Item {
id: number;
name: string;
location: "equipment" | "magazine" | "shop" // | and other in future...
}
class AppState {
items: Item[];
}
const getItems = (store: Store): Observable<Item[]> => {
return store.select((appStore: AppStore) => appStore.items);
}
const getItemsInEquipment = (store: Store): Observable<Item[]> => {
const items$: Observable<Item[]> = getItems(store);
return items$.pipe(
map(items => items.filter(item => item.location === "equipment"))
);
}
const getItemsInMagazine = (store: Store): Observable<Item[]> => {
const items$: Observable<Item[]> = getItems(store);
return items$.pipe(
map(items => items.filter(item => item.location === "magazine"))
);
}
const getItemsInShop = (store: Store): Observable<Item[]> => {
const items$: Observable<Item[]> = getItems(store);
return items$.pipe(
map(items => items.filter(item => item.location === "shop"))
);
}或者..。
多状态
class Item {
id: number;
name: string;
}
class AppState {
itemsInEquipment: Item[];
itemsInMagazine: Item[];
itemsInShop: Item[];
// | and other in future...
}
const getItemsInEquipment = (store: Store): Observable<Item[]> => {
return store.select((appStore: AppStore) => appStore.itemsInEquipment);
}
const getItemsInMagazine = (store: Store): Observable<Item[]> => {
return store.select((appStore: AppStore) => appStore.itemsInMagazine);
}
const getItemsInShop = (store: Store): Observable<Item[]> => {
return store.select((appStore: AppStore) => appStore.itemsInShop);
}
const getItems = (store: Store): Observable<Item[]> => {
const itemsInEquipment$: Observable<Item[]> = getItemsInEquipment(store);
const itemsInMagazine$: Observable<Item[]> = getItemsInMagazine(store);
const itemsInShop$: Observable<Item[]> = getItemsInShop(store);
return combineLatest([itemsInEquipment$, itemsInMagazine$, itemsInShop$]);
}这两种方法的优缺点是什么?
发布于 2020-10-17 08:56:52
我建议采取另一种方法。例如,在NgRx中,我们将为所有Items设置一个单一的实体状态,然后将Items的In数组存储在每个列表中。NGXS实验室有一个实体状态适配器,值得一试。
基本上,所有的Items都存储在一个对象中,其中键是每个Item的id字段。
itemEntities: {
itemId1: Item,
itemId2: Item,
itemId3: Item
}这允许直接查找,并防止因Array操作而造成的性能损失。
然后,您的每个itemsInEquipment、itemsInStore等都是简单的ids数组,允许您从实体状态获取它们。
https://stackoverflow.com/questions/64398362
复制相似问题