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

相关内容

热门资讯

一分钟揭秘“宝宝浙江游戏开挂器... 宝宝浙江游戏开挂器开挂教程视频分享装挂详细步骤在当今的网络游戏中,宝宝浙江游戏开挂器作为一种经典的娱...
记者揭秘“微乐河南麻将辅助io... 记者揭秘“微乐河南麻将辅助ios”开挂(透视)辅助工具揭秘攻略(有挂教程);无需打开直接搜索微信(1...
推荐十款“aapoker免费透... 大家好,今天小编来为大家解答aapoker免费透视脚本这个问题咨询软件客服可以免费测试直接加微信(1...
透视安卓版“中至小程序破檞”开... 【亲,中至小程序破檞 这款游戏可以开挂的,确实是有挂的,很多玩家在这款中至小程序破檞中打牌都会发现很...
重大推荐“约战丹东苹果辅助”开... 重大推荐“约战丹东苹果辅助”开挂(透视)辅助平台靠谱教程(有挂教程)约战丹东苹果辅助ai黑科技系统规...
避坑细节“新海贝之城开挂”开挂... 避坑细节“新海贝之城开挂”开挂(透视)辅助神器2026新版技巧(了解有挂);无需打开直接搜索打开薇:...
玩家实测“九游辅助器”开挂(透... 九游辅助器 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由: 1、软件...
最新技巧“sohoo开挂辅助”... sohoo开挂辅助是一款专注玩家量身打造的游戏记牌类型软件,在sohoo开挂辅助这款游戏中我们可以记...
分享一款“盛世辅助”开挂(透视... 大家好,今天小编来为大家解答盛世辅助这个问题咨询软件客服可以免费测试直接加微信(136704302)...
透视软件“闽游十三水辅助”开挂... 透视软件“闽游十三水辅助”开挂(透视)辅助脚本揭秘攻略(有挂技术) 【无需打开直接搜索加薇13670...