[英]How to set state value in Ngrx 9.x?
我试图弄清楚如何在最新版本的 Ngrx 中设置特定值。 文档提到了如何在商店中增加/减少/重置值,但我没有看到任何关于如何动态设置值或如何将 arguments 传递给减速器的示例。
这是我目前所拥有的,但我知道这是不正确的:
我的行动:
// TODO: properly implement action
export const setLabel = createAction('[Label Component] Set, props<{ addressField: string }>()');
我的减速机:
export interface AppState {
addressField;
}
const _reducer = createReducer(
// initial state:
{ addressField: '' },
// TODO: update `addressField`:
on(setLabel, state => {
return {
...state
};
})
);
export function labelReducer(state, action) {
return _reducer(state, action);
}
最后,我的组件:
// imports...
export class MyComponent implements OnInit {
constructor( private store: Store<AppState>,
private AddressService: AddressService) {
}
ngOnInit() {
// TODO: update store state:
this.AddressService.getFields().subscribe(x => {
this.store.dispatch(setLabel({ addressField: x.addressLine }));
});
}
}
动作.ts
export enum ActionTypes {
SetLabel = '[Label Component] Set'
}
export const SetLabel = createAction(ActionTypes.SetLabel, props<{ addressField: string }>());
减速器.ts
export interface AppState {
addressField;
}
export initialState: AppState = {
addressField: ''
}
const _reducer = createReducer(
initialState,
on(SetLabel, (state, { addressField }) => {
return {
...state,
addressField
};
})
);
您的组件很好,在处理副作用(异步数据)时最好使用效果
on(setLabel, state => {
return {
...state,
propToUpdate: 'foo'
};
})
on(setLabel, (state, action) => {
return {
...state,
propToUpdate: action.propToSet
};
})
有关更多信息,请参阅扩展语法。
或者,只需使用ngrx-etc
const entityReducer = createReducer<{ entities: Record<number, { id: number; name: string }> }>(
{
entities: {},
},
mutableOn(create, (state, { type, ...entity }) => {
state.entities[entity.id] = entity
}),
mutableOn(update, (state, { id, newName }) => {
const entity = state.entities[id]
if (entity) {
entity.name = newName
}
}),
mutableOn(remove, (state, { id }) => {
delete state.entities[id]
}),
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.