【问题标题】:update root state from feature state ngrx从特征状态 ngrx 更新根状态
【发布时间】:2018-12-05 10:12:20
【问题描述】:

我有一个使用 ngrx 显示博客的应用

主根状态如下

import { Blog } from '../models/blog';

export interface AppState {
  readonly loaded: boolean;
  readonly blogs: {[key:number]:Blog}
}

export const initialState:AppState = {
  loaded: false,
   blogs: {}
}

我还设置了一个功能模块来管理博客

StoreModule.forFeature('crudBlog', reducers)

我现在想知道的是;当我想更新、删除等博客时,如何从功能缩减文件访问我的商店的 AppState(根状态)

所以我可以做这样的事情;

function handleBlogUpdatedAction(state, action){
    const index = action.payload.index;
    const newState = Object.assign({}, rootState);
    newState[index] = action.payload.blog
return newState;
}

或者有没有更好的方法?

【问题讨论】:

    标签: angular ngrx


    【解决方案1】:

    ngrx 状态被认为是不可变的,您通过分配newState[index] = action.payload.blog 来更改状态。

    例如,这就是你的 reducer 的样子:

    export function reducer(
      state = initialState,
      action
    ) : BlogState {
        switch (action.type) {
            case UPDATED_BLOG_SUCCESS: {
                const blog = action.payload;
                const entites = {
                    ...state.entities,
                    [blog.id]: blog
                };
    
                // below is how your new state is returned using the spread operator
                return {
                    ...state,
                    entities
                };
            }
        }
    }
    

    initialState 是:

    export interface BlogState {
        entities: { [id: number]: Blog };
        loaded: boolean;
        loading: boolean;
    }
    
    export const initialState : BlogState = {
      entities: {},
      loaded: false,
      loading: false,
    };
    

    【讨论】:

    • 嗨,感谢您的回答,问题是我认为一旦我使用“Object.assign”,那么该对象现在可以被变异,我遇到的问题是我需要访问 root从功能状态“CrudBlogState”状态“AppState”这可能吗?
    • 我很少需要这样做,如果我记得你必须使用 selector 从另一个功能状态获取状态。
    • @Roy,也许这会对你有所帮助,github.com/ngrx/example-app/issues/159 见评论底部。
    • 谢谢,我去看看
    猜你喜欢
    • 1970-01-01
    • 2022-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2018-10-16
    • 2019-01-10
    • 1970-01-01
    相关资源
    最近更新 更多