ngRx Store-Reducer返回undefined-Store.select()未定义



这是我第一次使用ngRx Store,实现了我的第一个效果。。

什么工作正常:

  • 与后端的通信
  • 操作正在后台执行(删除、添加、获取(
  • 有效载荷正在从效果中到达减速器(记录以确保(

所以我的问题是我无法从我的reducer中获取数据。如果我从组件中的存储中选择数据,我会在组件中获得未定义的数据。我点击了效果中的数据,数据被错误地传递了。还记录了减速器中的数据——它就在那里。但当它被返回时,它会返回undefined。ReDux Devtools记录一切正常。最后但同样重要的是。。即使使用固定值,状态也不会更新,就像加载时使用true/false的布尔值一样。

Le代码:

//在哪里我得到了未定义的

export class ProfileComponent implements OnInit {
user: any;
items$: Observable<Product[]>;
loading$: Observable<boolean>;
error$: Observable<Error>;
newItem: Product = {id: 0, name:""};
constructor(private keycloakService: KeycloakService, private store: Store<ProductState>, private productService: ProductService) { }
ngOnInit(): void {
this.productService.setToken(this.keycloakService.getToken());
this.user = this.keycloakService.getUsername();
this.items$ = this.store.select(store => store.list);
this.loading$ = this.store.select( store => store.loading);
this.error$ = this.store.select( store => store.error);
this.store.dispatch(new LoadProduct());
this.items$.subscribe(val => console.log(val));
this.loading$.subscribe(val => console.log(val));
this.error$.subscribe(val => console.log(val));
}

//还原剂

export type Action = Products.All;
const initialState: ProductState = {
list: [],
loading: false,
error: undefined
}
const newState = (state, newData) => {
return Object.assign({}, state, newData);
}
export function reducer(state: ProductState = initialState, action: Action) : ProductState{
console.log(action.type, state);
switch (action.type) {
case Products.LOAD_PRODUCT: return { ...state, loading: true};
case Products.LOAD_PRODUCT_SUCCESS: return newState(state, {list: action.payload, loading: false, error: undefined});
case Products.LOAD_PRODUCT_FAILURE: return { ...state, error: action.payload, loading: false};
case Products.ADD_PRODUCT: return { ...state, loading: true};
case Products.ADD_PRODUCT_SUCCESS: return { ...state, list: action.payload, loading: false};
case Products.ADD_PRODUCT_FAILURE: return { ...state, error: action.payload, loading: false};
case Products.REMOVE_PRODUCT: return { ...state, loading: true};
case Products.REMOVE_PRODUCT_SUCCESS: return { ...state, list: state.list.filter(item => item.id !== action.payload), loading: false};
case Products.REMOVE_PRODUCT_FAILURE: return { ...state, error: action.payload, loading: false};
default: return state;
}

我非常感谢你的帮助:(

您应该使用选择器函数从存储中获取数据:https://ngrx.io/guide/store/selectors

为了快速解锁,我打赌.list, .loading, .errorstate上是未定义的。

试着这样调试:

// see how the whole store looks like
this.store.subscribe(state => console.log({ state }));

对你来说,我看到它与products有关,所以我打赌它应该是这样的:

this.items$ = this.store.select(store => store.products.list);
this.loading$ = this.store.select( store => store.products.loading);
this.error$ = this.store.select( store => store.products.error);

最新更新