angular - ngrx/store 未显示表单的更新值

标签 angular redux ngrx ngrx-store ngrx-effects

我需要输入 2 个输入值,通过表单显示存储空间的使用情况(已用空间和剩余空间),并显示从 ngrx/Store 输入的值。每次提交表单时,都会显示新值并更新旧值。问题是 UI 始终显示(used_space 和剩余空间)的默认值,我不知道我的架构是否正确,因为我是 ngrx/store 的新手。

模型(usage.model.ts):

   export interface Usage {
      used_space: number;
      remaining_space: number;
    }

操作(usage.actions.ts):
export const EDIT_USAGE  = '[Usage] Edit';
...
export class EditUsage implements Action {
  readonly type = EDIT_USAGE
  constructor(public payload: Usage) {}
}
...
export type All = Reset | EditUsage;

reducer (usage.reducer.ts):
导出类型 Action = UsageActions.All;
/// Default app state
const defaultState: Usage = {
  used_space: 2,
  remaining_space: 3
}

/// Helper function to create new state object
const newState = (state, newData) => {
  return Object.assign({}, state, newData)
}

export function usageReducer(state: Usage = defaultState, action: Action) {
  switch(action.type) {
    case UsageActions.EDIT_USAGE:
      // return [...state, action.payload];
      return newState(state, { Usage: action.payload });
    case UsageActions.RESET:
      return defaultState;
    default:
      return state;
  }
}

在 app.component.ts 中:
  usage: Observable<Usage>

  constructor(private store: Store<AppState>) {
    this.usage = this.store.select('usage')
  }

  editUsage(used_space,remaining_space) {
    this.store.dispatch(new UsageActions.EditUsage({used_space:used_space , remaining_space:remaining_space}) )
  }

在 app.component.html 中:
<input type="text"  #used_space>
<input type="text"  #remaining_space>
<button (click)="editUsage(used_space.value,remaining_space.value)" >Edit Space</button>

<div *ngIf="usage | async as u">
  <h2>Used space: {{ u.used_space }}</h2>
  <h2>remaining space: {{ u.remaining_space }}</h2>
</div>

我没有看到任何结果,我不知道出了什么问题。

最佳答案

问题在于您的 reducer :

switch(action.type) {
  case UsageActions.EDIT_USAGE:
    return newState(state, { Usage: action.payload }); <<--------
}
您正在传递先前的状态和 new object with usage as a property Object.assign 的作用是:创建一个新对象,将之前的状态附加到它,附加一个全新的属性 Usage 并将 store 的新值添加到它。这是新创建的对象的 View :

你可以直接通过 payload 解决这个问题:
switch(action.type) {
  case UsageActions.EDIT_USAGE:
    return newState(state, action.payload);
}
Working Demo
另外,只要您在 reducer 中更新整个对象,我相信您也不需要 Object.assign()。您可以直接返回 action.payload,因为它是新状态。

关于angular - ngrx/store 未显示表单的更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50839592/

相关文章:

angular - 使用 RxJs Pipe 将 Observable 减少为不同的类型

javascript - Redux useSelector 过滤对象?

angular - 为什么 ngrx/redux 效果必须返回 Action ?使用像 elm 这样的 noop Action 是否被认为是不好的做法?

angular - 使用filter()代替ofType()可以吗

angular - Breezejs、Angular 2 和 OData

angular - Google 图表无法在 Materialise Accordion 中工作

javascript - react native + Redux : How to properly pass in props to action callers?

javascript - 将 React 本地状态与 Redux 全局状态相结合

angular - 如何在 Angular 中的 store 上实现错误处理

javascript - 在 protractor.conf.js 中找不到模块浏览器?