我有一个使用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;
}
还是有更好的方法?
答案 0 :(得分:1)
ngrx状态是不可变的,您可以通过为其分配状态newState[index] = action.payload.blog
来更改状态。
例如,这就是您的减速器的外观:
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,
};