Tig*_*sus 5 redux ngrx ngrx-effects angular ngrx-store
我需要通过表单输入 2 个输入值,以兆字节为单位显示存储空间的使用情况(已使用空间和剩余空间),并显示来自 ngrx/Store 的输入值。每次提交表单时,都会显示新值并更新旧值。问题是 UI 始终显示(used_space 和剩余空间)的默认值,并且我不知道我的架构是否正确,因为我是 ngrx/store 的新手。
模型(usage.model.ts):
export interface Usage {
used_space: number;
remaining_space: number;
}
Run Code Online (Sandbox Code Playgroud)
操作(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;
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
在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}) )
}
Run Code Online (Sandbox Code Playgroud)
在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>
Run Code Online (Sandbox Code Playgroud)
我没有看到任何结果,我不知道出了什么问题。
问题在于你的reducer:
switch(action.type) {
case UsageActions.EDIT_USAGE:
return newState(state, { Usage: action.payload }); <<--------
}
Run Code Online (Sandbox Code Playgroud)
您正在通过先前的状态和new object with usage as a property. 作用Object.assign是:创建一个新对象,向其附加先前的状态,附加一个全新的属性Usage并向其添加新的存储值。这是新创建的对象的视图:
您可以payload直接通过以下方式解决此问题:
switch(action.type) {
case UsageActions.EDIT_USAGE:
return newState(state, action.payload);
}
Run Code Online (Sandbox Code Playgroud)
另外,只要您在减速器中更新整个对象,我相信您也不需要Object.assign()。您可以直接返回,action.payload因为它是新状态。
| 归档时间: |
|
| 查看次数: |
7245 次 |
| 最近记录: |