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 语法问题。

相关内容

热门资讯

八分钟辅助挂!新九哥智能辅助软... 八分钟辅助挂!新九哥智能辅助软件,小闲川南可以辅助,微扑克教程(有挂秘诀)1、游戏颠覆性的策略玩法,...
透视新版!wepoker私人局... 透视新版!wepoker私人局透视插件,wepoker轻量版有透视,必备教程(有挂助手);致您一封信...
5分钟辅助挂!潮汕汇破解版,w... 5分钟辅助挂!潮汕汇破解版,wepoker开挂事件,新版2025教程(有挂解惑)1、点击下载安装,插...
透视安装!wepoker私局代... 透视安装!wepoker私局代打,来玩app 德州 辅助,必备教程(有挂秘笈);透视安装!wepok...
辅助透视!德州局透视脚本免费版... 辅助透视!德州局透视脚本免费版下载手机版,aapoker发牌逻辑,微扑克教程(有挂秘诀);1、点击下...
三分钟辅助挂!边锋斗地主微信小... 三分钟辅助挂!边锋斗地主微信小程序插件,小程序牵手跑得辅助,技巧教程(竟然有挂)1、全新机制【软件透...
四分钟辅助挂!约战武汉辅助插件... 四分钟辅助挂!约战武汉辅助插件,捉住捣蛋鸡作弊码,爆料教程(果真有挂)1、系统规律教程、辅助透视等服...
透视系统!wepoker黑侠破... 透视系统!wepoker黑侠破解,wepoker私人局俱乐部辅助,德州教程(有挂教程)是一款可以让一...
八分钟辅助挂!人海大厅软件辅助... 八分钟辅助挂!人海大厅软件辅助,凑一桌游戏辅助2023,实用技巧(有挂分享)1、游戏颠覆性的策略玩法...
透视了解!hhpoker可以控... 透视了解!hhpoker可以控制牌,wepoker透视脚本是有挂,必赢方法(有挂攻略);透视了解!h...