[英]How to export the reducer function and add it to the storeModule.forRoot in Angular?
我是 ngrx 的新手,正在從他們的網站ngrx.io閱讀 ngrx 文檔。 我在他們的 reducer 中偶然發現了一些代碼,但我不明白。
這是 counter.actions.ts 文件
import { createAction } from '@ngrx/store';
export const increment = createAction('[Counter Component] Increment');
export const decrement = createAction('[Counter Component] Decrement');
export const reset = createAction('[Counter Component] Reset');
這是 counter.reducer.ts 文件。
import { createReducer, on } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';
export const initialState = 0;
const _counterReducer = createReducer(
initialState,
on(increment, (state) => state + 1),
on(decrement, (state) => state - 1),
on(reset, (state) => 0)
);
export function counterReducer(state, action) {
return _counterReducer(state, action);
}
這是應用程序模塊文件
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { StoreModule } from '@ngrx/store';
import { counterReducer } from './counter.reducer';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, StoreModule.forRoot({ count: counterReducer })],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
我的問題如下:
export function counterReducer(state, action) {
return _counterReducer(state, action);
}
在減速器文件中?
是否需要 counterReducer?
為什么不單獨導出 _counterReducer 並將其添加到應用程序模塊文件中的 storeModule.forRoot 中。
我在 ngrx 網站上閱讀有關 action 的文章時看到了這些
導出的 reducer function 是必需的,因為 View Engine AOT 編譯器不支持 function 調用。 如果您使用默認的 Ivy AOT 編譯器(或 JIT),則不再需要它。
這是一個可能的解釋嗎?
我相信以下方法會起作用,通過另一個 function 重新導出的額外步驟沒有實際意義,因為它實際上沒有任何作用。
import { createReducer, on } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';
export const initialState = 0;
const counterReducer = createReducer(
initialState,
on(increment, (state) => state + 1),
on(decrement, (state) => state - 1),
on(reset, (state) => 0)
);
1,2). 您的 reducer 必須導出 reduce 方法/函數。 您可以按照@wscttc 的建議將其導出。 如果您的 reducer 返回更復雜的 object,您甚至可以為響應添加一個類型。
import { createReducer, on } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';
const initialState = 0;
export const counterReducer = createReducer<number>(
initialState,
on(increment, (state) => state + 1),
on(decrement, (state) => state - 1),
on(reset, (state) => 0)
);
3). 主要思想是具有特征狀態。 隨着您的應用程序的增長,明智的做法是擁有多個具有自己的 reducer、effects 和 actions 的功能狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.