【问题标题】:Cannot initialize the state of ngrx (v. 4.x) store无法初始化 ngrx (v. 4.x) 存储的状态
【发布时间】:2017-08-25 13:38:20
【问题描述】:

我目前正在研究使用 ngrx 存储 (v. 4.0.3) 进行状态管理。这似乎是一个很棒的项目。

我在尝试初始化商店的状态时遇到了一些障碍。 documentation 让它看起来很简单,但我看不到哪里出错了。

这里是相关代码sn-ps:

在 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 的输入,控制台确实会记录正确的值。所以看来我已经正确设置了商店。

我可能缺少一些真正简单的东西。谁能给点建议?

【问题讨论】:

    标签: ngrx-store ngrx-store-4.0


    【解决方案1】:

    由于您将其命名为readonly,因此您不能分配该值,

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

    您需要使用dispatch 语句发送值

    this.store.dispatch(new UpdateSearchTextAction.UPDATE(<<string>>));
    

    【讨论】:

    • 你的建议是我已经在做的,但只是为了响应用户输入。我想弄清楚的是如何在不调度 Action 的情况下设置 AppState 的初始状态。由于 StoreModule.forRoot 的签名需要一个 reducer 和一个 StoreConfig,我认为它们可用于初始化状态,我不知所措。我不想要的是我在商店里的所有状态都是用 undefined 初始化的。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 2020-08-30
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      相关资源
      最近更新 更多