gpt4 book ai didi

angular - 与@ngrx/store 一起使用时,@ngrx/entity `Cannot read property ' ids' of undefined`?在定义适配器时已经考虑了自定义 ID

转载 作者:行者123 更新时间:2023-12-03 21:18:07 29 4
gpt4 key购买 nike

我已经查看了关于此的另外 2 篇文章,其中包含较大状态的一篇不适用,而另一篇注册了多个 forFeature - 我已经对此进行了一些测试,即使我在之前或之后导入它forRoot(reducers) 在我的 app.module 中,它没有区别。

我确定我在配置中遗漏了一些明显的东西。

我的配置:

export const orderAdapter: EntityAdapter<IOrder> = createEntityAdapter<IOrder>({
selectId: (order: IOrder) => order._id
});

export interface AllOrdersState extends EntityState<IOrder> {}

export const initialState: AllOrdersState = orderAdapter.getInitialState({
ids: [],
entities: {}
});

export const OrdersState = createFeatureSelector<AllOrdersState>('orders');

export const {
selectIds,
selectEntities,
selectAll,
selectTotal
} = orderAdapter.getSelectors(OrdersState);

我的实际 reducer :

export function ordersReducer(
state: AllOrdersState = initialState,
action: actions.OrdersActions
) {
case actions.CREATE_MANY: {
console.log(action.orders);
return orderAdapter.addMany(action.orders, state);
}
}

我在我的 Order.Module 中注册为:
    StoreModule.forFeature('orders', ordersReducer),

我的主要 reducer map :
const reducers: ActionReducerMap<AppState> = {
order: orderReducer,
admin: adminReducer,
tlabs: tlabsReducer,
reports: reportsReducer,
settings: settingsReducer,
orders: ordersReducer
};


然后是app.module中的主要导入:
    StoreModule.forRoot(reducers),

尝试读取实体:

构造函数:
 private store: Store<AppState>

实际功能:
this.store
.select(ordersReducer.selectAll)

该导入的来源:
import * as ordersReducer from '../../../../../store/reducers/orders.reducer';

最佳答案

我在 entity.js(NGRX 实现文件)中遇到了与您类似的错误。就我而言,我有一个延迟加载的模块,它有自己的状态,最初是未定义的。由于实体选择器在获取实体相关字段(例如 ids)之前不做任何空检查,因此会导致此错误。我的解决方案是避免使用 orderAdapter.getSelectors(OrdersState)而是定义我自己的相当简单的 protected 选择器:

export const selectIds = createSelector(selectOrderState, (state) => state?.ids);
export const selectEntities = createSelector(selectOrderState, (state) => state?.entities);
export const selectAll = createSelector(selectOrderState, (state) => (state?.ids as Array<string|number>)?.map(id => state?.entities[id]));
export const selectTotal = createSelector(selectOrderState, (state) => state?.ids?.length);

我不喜欢我没有使用内置选择器的事实,但至少这不会破坏我的代码。我希望 NGRX 团队提供一种方法来避免这种情况。

关于angular - 与@ngrx/store 一起使用时,@ngrx/entity `Cannot read property ' ids' of undefined`?在定义适配器时已经考虑了自定义 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58198863/

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