0

我目前正在研究使用 ngrx 商店(v. 4.0.3)进行状态管理。这似乎是一个伟大的项目。

在尝试初始化商店状态时,我遇到了一些障碍。该文档使它看起来相当简单,但我无法看到我哪里出错了。

以下是相关的代码片段:

在 app.state.ts

export interface AppState {
    searchText: string;
}

在 search-text.reducer.ts

export const UPDATE = 'UPDATE';

export class UpdateSearchTextAction implements Action {
    readonly type: string = UPDATE;
    constructor(public readonly text: string) {}
}

export function searchTextReducer(state: string, action: UpdateSearchTextAction) {
    switch(action.type) {
      case UPDATE:
        return action.text;
    }
};

在 app.module.ts

export const reducers: ActionReducerMap<AppState, UpdateSearchTextAction> = {
    searchText: searchTextReducer
};

export const initialState: InitialState<AppState> = {
    searchText: 'sds'
};

....

imports: [
....
StoreModule.forRoot(reducers, initialState)
]

在某些组件中

constructor(private store: Store<AppState>) {
    this.searchBoxText = store.select('searchText');
    this.searchBoxText.subscribe(text => console.log('value = [' + text + "]"));
}

因此,当应用程序加载时,我希望看到以下记录到控制台:

value = [sds]

但我看到

value = [undefined]

稍后,一旦我开始输入触发 UpdateSearchTextAction 的输入,控制台确实会记录正确的值。所以看起来我已经正确设置了商店。

我可能缺少一些真正简单的东西。任何人都可以提供一些建议吗?

4

2 回答 2

0

state如果没有操作匹配,您必须为参数指定默认值并返回相同的状态。尝试将减速器更改为以下内容:

export function searchTextReducer(state: string = '', action: UpdateSearchTextAction) {
    switch(action.type) {
      case UPDATE:
        return action.text;
      default:
        return state;
    }
};
于 2017-09-01T00:44:34.983 回答
0

由于您拥有它,因为readonly您不允许分配值,

export class UpdateSearchTextAction implements Action {
    readonly type: string = UPDATE;
    constructor(public text: string) {}
}

并且您需要使用dispatch语句发送值

this.store.dispatch(new UpdateSearchTextAction.UPDATE(<<string>>));
于 2017-08-26T14:27:31.193 回答