gpt4 book ai didi

javascript - 如何在 Ngrx 9.x 中设置状态值?

转载 作者:行者123 更新时间:2023-12-05 05:01:47 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何在最新版本的 Ngrx 中设置特定值。文档提到了如何在商店中递增/递减/重置值,但我没有看到任何关于如何动态设置值或如何将参数传递给 reducer 的示例。

这是我目前拥有的,但我知道这是不正确的:

我的行为:

// TODO: properly implement action
export const setLabel = createAction('[Label Component] Set, props<{ addressField: string }>()');

我的 reducer :

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 }));
});
}
}

最佳答案

Action .ts

export enum ActionTypes {
SetLabel = '[Label Component] Set'
}
export const SetLabel = createAction(ActionTypes.SetLabel, props<{ addressField: string }>());

reducer.ts

export interface AppState {
addressField;
}

export initialState: AppState = {
addressField: ''
}

const _reducer = createReducer(
initialState,
on(SetLabel, (state, { addressField }) => {
return {
...state,
addressField
};
})
);

你的组件很好,在处理 Side Effects(异步数据)时最好使用 Effects

关于javascript - 如何在 Ngrx 9.x 中设置状态值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62581360/

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