gpt4 book ai didi

NGRX - 结合选择器和 Prop

转载 作者:行者123 更新时间:2023-12-01 00:21:52 25 4
gpt4 key购买 nike

当其中一个需要 Prop 时,如何组合 reducer ?

我有以下型号:

interface Device {
id: string;
data: IDeviceData;
}

和 DeviceReducer 如下所示:
import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';
import { Device } from '../model/device';
import { SubnetBrowserApiActions } from 'src/app/explorer/actions';

export interface State extends EntityState<Device> { }

export const adapter: EntityAdapter<Device> = createEntityAdapter<Device>();

export const initialState: State = adapter.getInitialState();

export function reducer(
state = initialState,
action:
| SubnetBrowserApiActions.SubnetBrowserApiActionsUnion
): State {
switch (action.type) {
case SubnetBrowserApiActions.SubnetBrowserApiActionTypes.LoadEntriesSucces: {
return adapter.upsertMany(action.payload.entries, state);
}

default: {
return state;
}
}
}

const {
selectAll,
} = adapter.getSelectors();

export const getAllDevices = selectAll;

在我的另一个 reducer 中,当我想使用一组 id 选择设备时,我使用以下代码:
export const getVisibleDrives = createSelector(
[fromRoot.getAllDevices, getVisibleDrivesSerialNumbers],
(devices, visibleDevicesIds) =>
devices.filter((device) => onlineDevicesIds.includes(device.serialNumber)),
);

这段代码非常重复,所以我想添加添加参数化选择器,这些选择器将只返回这些驱动器,这些驱动器在我作为 Prop 传递的数组中具有 id。我试图做的事情如下:

DeviceReduced 中的附加选择器
export const getDrivesWithIds = (ids: string[]) => createSelector(
getAllDevices,
devices => devices.filter(device => ids.includes(device.id))
);

然后将它们组合在 中关注 道路:
export const getVisibleDrives = createSelector(
getVisibleDrivesSerialNumbers,
(ids) => fromRoot.getDrivesWithIds
);

这里的问题是这个选择器的返回类型是
(ids: string[]) => MemoizedSelector<State, Device[]>
这使我无法对这个选择器做任何有用的事情。例如,我想按关键字过滤此列表,但我无法使用 filter方法:

示例用法
export const getFilteredVisibleDrives = createSelector(
[getVisibleDrives, getKeywordFilterValue],
(visibleDrives, keywordFilter) => {
return visibleDrives
.filter(drive => // in this line there is an error: Property 'filter' does not exist on type '(ids: string[]) => MemoizedSelector<State, Device[]>'
drive.ipAddress.toLowerCase().includes(keywordFilter.toLowerCase()) ||
drive.type.toLowerCase().includes(keywordFilter.toLowerCase()) ||
drive.userText.toLowerCase().includes(keywordFilter.toLowerCase())
);
},
);

最佳答案

选择器:

export const getCount = () =>   
createSelector(
(state, props) => state.counter[props.id],
(counter, props) => counter * props.multiply
);

成分:
this.counter2 = this.store.pipe(
select(fromRoot.getCount(), { id: 'counter2', multiply: 2 })
);
this.counter4 = this.store.pipe(
select(fromRoot.getCount(), { id: 'counter4', multiply: 4 })
);

看我的帖子 NgRx: Parameterized selectors
了解更多信息。

关于NGRX - 结合选择器和 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54707140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com