Angularngrxstorereducer语法问题
创始人
2024-10-28 18:00:35
0
  1. 在 reducers/index.ts 文件中,确保使用的 reducer 函数返回一个合法的 state,且 state 的类型需要和 interface 中声明的一致。

例如:

import { ActionReducerMap } from '@ngrx/store'; import { AppState } from '../models/app-state.model'; import { reducer as productReducer } from './product.reducer'; import { reducer as cartReducer } from './cart.reducer';

export const reducers: ActionReducerMap = { products: productReducer, cart: cartReducer };

  1. 在 reducer 函数中,确保所有的 case 分支都返回一个新的 state,而不是修改原先的 state。

例如:

import { ProductActionTypes, ProductActions } from '../actions/product.actions';

export interface ProductState { products: Array; };

export const initialState: ProductState = { products: [] };

export function reducer(state = initialState, action: ProductActions): ProductState { switch (action.type) { case ProductActionTypes.LoadProductsSuccess: { return { ...state, products: action.payload }; } default: { return state; } } }

  1. 在使用 reducer 函数的组件中,需要声明当前组件需要订阅的 state 数据,并通过 map 函数将其映射到组件中的变量。

例如:

import { Component, OnInit } from '@angular/core'; import { Store } from '@ngrx/store'; import { ProductState } from '../reducers/product.reducer'; import { LoadProducts } from '../actions/product.actions'; import { Observable } from 'rxjs/Observable'; import { Product } from '../models/product.model';

@Component({ selector: 'app-product-list', templateUrl: './product-list.component.html', styleUrls: ['./product-list.component.css'] }) export class ProductListComponent implements OnInit { products$: Observable>;

constructor(private store: Store) {}

ngOnInit() { this.store.dispatch(new LoadProducts()); this.products$ = this.store.select('products'); }

}

通过以上三个步骤,可以避免在 Angular ngrx store 中出现 reducer 语法问题。

相关内容

热门资讯

在玩家背景下!poker ma... 在玩家背景下!poker master辅助,hhpoker有没有辅助,窍门教程(有挂助手)-哔哩哔哩...
出现新变化!wepokerh5... 出现新变化!wepokerh5破解,hhpoker透视脚本,模板教程(有挂猫腻)-哔哩哔哩进入游戏-...
据目击者称!四川换三张辅助器,... 据目击者称!四川换三张辅助器,微信开心泉州辅助,总结教程(其实确实有挂的)-哔哩哔哩微信开心泉州辅助...
此事引发广泛关注!wepoke... 此事引发广泛关注!wepoker辅助是真的假的,哈糖大菠萝有挂吗,烘培教程(发现有挂)-哔哩哔哩1、...
反观!起点休闲辅助,小闲辅助软... 您好,起点休闲辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在...
为了进一步!德普之星透视辅助软... 为了进一步!德普之星透视辅助软件,wepoker透视脚本免费使用视频,妙招教程(有挂助手)-哔哩哔哩...
出现新变化!皮皮跑子胡子,微信... 出现新变化!皮皮跑子胡子,微信微乐游戏辅助脚本,手段教程(原来真的有挂的)-哔哩哔哩1、进入游戏-大...
相较于以往!we poker游... 相较于以往!we poker游戏下,hhpoker怎么防辅助,方案教程(有挂解密)-哔哩哔哩1、每一...
最新消息!新道游开挂辅助透视,... 您好,新道游开挂辅助透视这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多...
据报道!哈糖大菠萝免费辅助器,... 据报道!哈糖大菠萝免费辅助器,wepoker轻量版有透视吗,要领教程(有挂教程)-哔哩哔哩;1、哈糖...