我刚刚通过学习教程开始尝试NGRX。到目前为止,一切似乎都可以正常工作,只是我的状态“数据结构化”以某种方式损坏了,而我根本找不到位置和方式。
我的减速机看起来像这样:
import * as fromRoot from '../../../state/app.state';
import { createFeatureSelector, createSelector } from '@ngrx/store';
export interface State extends fromRoot.State {
criteriaLock: CriteriaLockState;
}
export interface CriteriaLockState {
storeNames: string[];
selectedStoreName: string;
}
const initialState: CriteriaLockState = {
storeNames: [],
selectedStoreName: ''
};
const getCriteriaLockFeatureState = createFeatureSelector<CriteriaLockState>('criteria-lock');
export const getStoreNames = createSelector(
getCriteriaLockFeatureState,
state => state.storeNames
);
export const getSelectedStoreName = createSelector(
getCriteriaLockFeatureState,
state => state.selectedStoreName
);
export function reducer(state = initialState, action): CriteriaLockState {
switch (action.type) {
case 'SET_STORE_NAMES':
return {
...state,
storeNames: action.payload
};
case 'SET_SELECTED_STORE_NAME':
return {
...state,
selectedStoreName: action.payload
};
default:
return state;
}
}
在订阅它并尝试通过以下方式访问selectedStoreName时
this.store.pipe(select(fromCriteriaLock.getSelectedStoreName)).subscribe(
criteriaLock => {
console.log(criteriaLock)
}
CriteriaLock是未定义的,因为接收的数据结构不是
criteria-lock: {
selectedStoreName: ''
}
但是
criteria-lock: {
reducer: {
selectedStoreName: ''
}
}
这意味着reducer函数以某种方式显示在状态Object中。 这不是正确的行为,对吗? 当我想访问订阅中的州时,必须将选择器更改为
export const getStoreNames = createSelector(
getCriteriaLockFeatureState,
state => state.**reducer**.storeNames
);
我不知道我如何在状态结构中粘贴该Property,而且我从未见过有人遇到相同的问题。在Reducer中记录状态对象时,我会收到正确的状态。仅在这里,我得到了这个减速器对象。这似乎是不正确的,因为该教程从未提到过类似的内容。
我通过以下方式设置商店名称:
this.store.dispatch({
type: 'SET_SELECTED_STORE_NAME',
payload: storeName
});
并在我的CriteriaLockModule中添加StoreModule
imports: [
CommonModule,
SharedModule,
FormsModule,
StoreModule.forFeature('criteria-lock', { reducer })
]
答案 0 :(得分:1)
我修复了它:
问题出在从模块导入的转义器周围的括号中。
imports: [
CommonModule,
SharedModule,
FormsModule,
StoreModule.forFeature('criteria-lock', **{ reducer }**)
]
应该是
imports: [
CommonModule,
SharedModule,
FormsModule,
StoreModule.forFeature('criteria-lock', **reducer**)
]
那只花了我3个小时:D