如何在NGRX商店中修改特定属性?

发布于 2025-02-05 08:23:22 字数 845 浏览 4 评论 0原文

我有一个像这样的还原器:

  export interface IVisitState {
      visits?: IVisit;
      redirects?: IVisitRedirect;
   }
  const initialState: IVisitState = {};
  const reducer = createReducer(
  initialState,
  on(fromActions.getVisitsListSuccess, (state, { payload }) => ({
    ...state,
    visits: payload,
  })),
  on(fromActions.getVisitRedirectsListSuccess, (state, { payload }) => ({
    ...state,
    redirects: payload,
  })),
);

访问的界面看起来像:

export interface IVisit {
  id: string;
  createdAt: string;
  lastUpdatedAt: string;
  guest: boolean;
}

从后端我获得了createat和lastupdatedat上的日期价值,但是在将它们显示在组件上之前,我已经使用Refert> Refert> RegralatdateField(dateValue:string)将它们显示为重新格式化。

我的问题是,如何在还原器上调用RegrialatdateField Fucntion,以便我不必在多个组件上使用此功能?

I have a reducer like that:

  export interface IVisitState {
      visits?: IVisit;
      redirects?: IVisitRedirect;
   }
  const initialState: IVisitState = {};
  const reducer = createReducer(
  initialState,
  on(fromActions.getVisitsListSuccess, (state, { payload }) => ({
    ...state,
    visits: payload,
  })),
  on(fromActions.getVisitRedirectsListSuccess, (state, { payload }) => ({
    ...state,
    redirects: payload,
  })),
);

the interface of the visits look like :

export interface IVisit {
  id: string;
  createdAt: string;
  lastUpdatedAt: string;
  guest: boolean;
}

From the backend I am getting a date value on createdAt and lastUpdatedAt, but before displaying them on the component I have reformat them using reformatDateField(dateValue: string).

My question is that, how can I call reformatDateField fucntion on reducer, so that I do not have to use this function on several component?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黄昏下泛黄的笔记 2025-02-12 08:23:22

您的问题的答案:

  on(fromActions.getVisitsListSuccess, (state, { payload }) => ({
    ...state,
    visits: {
       ...payload,
       createdAdd(dateValue: string),
       updatedAdd(dateValue: string),
    },
  })),

更好的答案:

理想情况下,这不是在还原器中进行的,而是在选择器中完成的。
您可以在多个组件中重复使用选择器,因此您还可以避免重复。

旁注,如果很难使用差异语法更新项目 - 请查看 ngrx-immer

The answer to your question:

  on(fromActions.getVisitsListSuccess, (state, { payload }) => ({
    ...state,
    visits: {
       ...payload,
       createdAdd(dateValue: string),
       updatedAdd(dateValue: string),
    },
  })),

Better answer:

Ideally, this isn't done in reducers, but in selectors.
You can reuse selectors in multiple components so you also avoid duplication.

Side note, if updating items using the spread syntax is hard - take a look at ngrx-immer

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文