簡體   English   中英

如何在 Ngrx 9.x 中設置 state 值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM