重置商店后的 Ngrx,组件调度一个动作
Ngrx after reseting the store, component dispatching an action
我已经为我的应用程序实现了商店。注销后我想重置商店。但是有个问题。
假设我有以下状态:
subjects: {
subjectsLoaded: true
}
在组件中,我订阅了这样的商店:
this.store.pipe(
select(areSubjectsLoaded),
tap((subjectsLoaded) => {
if (!subjectsLoaded) {
this.store.dispatch(loadSubjects());
console.log('Dispatching Subjects because they are not Loaded');
}
}),
filter(subjectsLoaded => subjectsLoaded),
takeUntil(this.unsubscribe$)
).subscribe();
注销并重置商店后,它看起来像:
subjects: {
subjectsLoaded: false
}
由于我订阅了组件中的更改,因此将进行操作调度。但我不知道如何防止这种情况。
我也在使用 takeUntil
以便在组件销毁后不接收数据
有一个小demo:
为了清除我正在使用 metaReducers 的商店:
export const metaReducers: MetaReducer<AppState>[] = [clearState];
export function clearState(reducer: ActionReducer<AppState>): ActionReducer<AppState> {
return (state: AppState, action: Action): AppState => {
if (action.type === '[Toolbar] User Logout') {
console.log('Clear state: ',state);
state = undefined;
}
return reducer(state, action);
};
}
我认为你必须使用 undefined
以外的其他东西,因为正如你所见,你无法再区分 'state has not been initialized' 和 'state must reset'。
您可以使用 symbol
来区分这些 状态 。
export const RESET_STATE = Symbol('reset state');
// your meta-reducer
state = RESET_STATE;
return state;
现在你可以这样认出它们了:
this.store.pipe(
filter(state => state !== RESET_STATE),
select(areSubjectsLoaded),
/* ... */
)
如果您不想重复自己的话,您可以根据该逻辑创建一个选择器并将其用于其他选择器。
我已经为我的应用程序实现了商店。注销后我想重置商店。但是有个问题。
假设我有以下状态:
subjects: {
subjectsLoaded: true
}
在组件中,我订阅了这样的商店:
this.store.pipe(
select(areSubjectsLoaded),
tap((subjectsLoaded) => {
if (!subjectsLoaded) {
this.store.dispatch(loadSubjects());
console.log('Dispatching Subjects because they are not Loaded');
}
}),
filter(subjectsLoaded => subjectsLoaded),
takeUntil(this.unsubscribe$)
).subscribe();
注销并重置商店后,它看起来像:
subjects: {
subjectsLoaded: false
}
由于我订阅了组件中的更改,因此将进行操作调度。但我不知道如何防止这种情况。
我也在使用 takeUntil
以便在组件销毁后不接收数据
有一个小demo:
为了清除我正在使用 metaReducers 的商店:
export const metaReducers: MetaReducer<AppState>[] = [clearState];
export function clearState(reducer: ActionReducer<AppState>): ActionReducer<AppState> {
return (state: AppState, action: Action): AppState => {
if (action.type === '[Toolbar] User Logout') {
console.log('Clear state: ',state);
state = undefined;
}
return reducer(state, action);
};
}
我认为你必须使用 undefined
以外的其他东西,因为正如你所见,你无法再区分 'state has not been initialized' 和 'state must reset'。
您可以使用 symbol
来区分这些 状态 。
export const RESET_STATE = Symbol('reset state');
// your meta-reducer
state = RESET_STATE;
return state;
现在你可以这样认出它们了:
this.store.pipe(
filter(state => state !== RESET_STATE),
select(areSubjectsLoaded),
/* ... */
)
如果您不想重复自己的话,您可以根据该逻辑创建一个选择器并将其用于其他选择器。