如何给 ngrx reducer/action 一个值来设置状态?
How to give a ngrx reducer/ action a value to set the state to?
我是第一次使用 Angular ngrx,我正在尝试用它替换我 'standard beginner-project' 中的所有 @Input() 和 @Output()。递增和递减状态很简单,但我想知道如何为 set Action 提供特定值以将状态设置为。
const _dividerReducer = createReducer(
initialState,
on(increment, (state) => state + 1),
on(decrement, (state) => state - 1),
on(set, (state) => initialState)
);
到目前为止,我已经尝试过类似的操作:
import { createAction } from "@ngrx/store";
export const set = (newValue:number) => createAction("[Divider Component] Set", { newValue });
但这显然不是它的工作方式 - 即使我看到 createAction() 中的第二个参数是配置。
看起来问题出在 reducer 文件中。您正在将状态重置为操作集的初始值,即 on(set, (state) => initialState).
set action 的 reducer 应该如下所示:
export interface IDividerState {
value:number;
}
export const initialState: IDividerState = {
value: 0
}
const _dividerReducer = createReducer(
initialState,
on(increment, (state) => state + 1),
on(decrement, (state) => state - 1),
on(set, (state, {payload}) => ({
value: payload
}));
然后您的 Set 操作应该具有您要设置的值的有效负载:
import { createAction, props } from "@ngrx/store";
export const set = createAction(
"[Divider Component] Set",
props<{ payload: number }>()
);
我是第一次使用 Angular ngrx,我正在尝试用它替换我 'standard beginner-project' 中的所有 @Input() 和 @Output()。递增和递减状态很简单,但我想知道如何为 set Action 提供特定值以将状态设置为。
const _dividerReducer = createReducer(
initialState,
on(increment, (state) => state + 1),
on(decrement, (state) => state - 1),
on(set, (state) => initialState)
);
到目前为止,我已经尝试过类似的操作:
import { createAction } from "@ngrx/store";
export const set = (newValue:number) => createAction("[Divider Component] Set", { newValue });
但这显然不是它的工作方式 - 即使我看到 createAction() 中的第二个参数是配置。
看起来问题出在 reducer 文件中。您正在将状态重置为操作集的初始值,即 on(set, (state) => initialState).
set action 的 reducer 应该如下所示:
export interface IDividerState {
value:number;
}
export const initialState: IDividerState = {
value: 0
}
const _dividerReducer = createReducer(
initialState,
on(increment, (state) => state + 1),
on(decrement, (state) => state - 1),
on(set, (state, {payload}) => ({
value: payload
}));
然后您的 Set 操作应该具有您要设置的值的有效负载:
import { createAction, props } from "@ngrx/store";
export const set = createAction(
"[Divider Component] Set",
props<{ payload: number }>()
);