求助:NgRx为何未生成包含初始heroSlides的预期状态?
问题:NgRx状态未包含HeroReducers初始状态
问题现象
控制台输出空对象,HeroReducer中定义的初始状态heroSlides数组未加载到store中。
已实现的代码
应用模块导入NgRx
imports: [ StoreModule.forRoot(reducers, {}) ],
Reducer注册文件(/ngrx/reducers/index.ts)
import { ActionReducerMap } from "@ngrx/store"; import { HeroReducers } from "../home/hero/hero.reducers"; export interface State {}; export const reducers: ActionReducerMap <State> = { heroReducers:HeroReducers }
HeroReducer代码
import { createReducer, on } from '@ngrx/store'; import * as heroActions from "./hero.actions"; const initialState = { heroSlides: [ { img: "Screenshot from 2024-01-20 12-38-48.png", status: "active" }, ] } export const HeroReducers = createReducer(initialState, on(heroActions.StoreHero, (state, action) => { console.log('Storesubjects.subjects', action) return { ...state, // subjects: action.subjects, }; }), )
Action文件代码
import { createAction, props } from "@ngrx/store"; export const StoreHero = createAction( '[Store Hero] Store Hero' )
组件中注入并使用Store
constructor( private store:Store<{heroReducers}> ) {} ngOnInit() { this.subscribeToReduxStores(); this.store.dispatch(StoreHero()); } private subscribeToReduxStores = () => { const hero$ = this.store.select((state) => { console.log('state', state) return state }) hero$.subscribe(hero => { // this.hero = hero; console.log('hero', hero) }) }
控制台输出
state {} hero {} state {}
问题原因及修复方案
1. State接口未定义状态分片类型
当前全局State接口为空,NgRx无法识别heroReducers这个状态分片的结构,导致初始状态无法正确映射到store中。
修复步骤:
- 在
hero.reducers.ts中导出状态类型:
import { createReducer, on } from '@ngrx/store'; import * as heroActions from "./hero.actions"; // 导出HeroState类型,描述该分片的状态结构 export interface HeroState { heroSlides: Array<{img: string; status: string}>; } const initialState: HeroState = { heroSlides: [ { img: "Screenshot from 2024-01-20 12-38-48.png", status: "active" }, ] } export const HeroReducers = createReducer(initialState, on(heroActions.StoreHero, (state, action) => { console.log('Storesubjects.subjects', action) return { ...state, // subjects: action.subjects, }; }), )
- 更新
/ngrx/reducers/index.ts中的全局State接口:
import { ActionReducerMap } from "@ngrx/store"; import { HeroReducers, HeroState } from "../home/hero/hero.reducers"; // 全局State接口包含heroReducers分片的类型定义 export interface State { heroReducers: HeroState; }; export const reducers: ActionReducerMap<State> = { heroReducers: HeroReducers }
2. 组件中Store泛型定义错误
当前组件中Store<{heroReducers}>未指定分片的具体类型,改为使用全局State接口确保类型一致。
修复步骤:
import { State } from '../ngrx/reducers'; // 导入全局State接口 constructor( private store: Store<State> ) {}
3. 订阅时精准选择状态分片
如果仅需获取heroReducers的数据,在select中指定具体路径,避免返回整个state:
private subscribeToReduxStores = () => { const hero$ = this.store.select(state => state.heroReducers); // 选择heroReducers分片 hero$.subscribe(hero => { console.log('hero', hero) // 此时会输出包含heroSlides的对象 }) }
验证修复
完成以上修改后重新运行应用,控制台输出应包含初始状态的heroSlides数组:
state { heroReducers: { heroSlides: [...] } } hero { heroSlides: [...] }
内容的提问来源于stack exchange,提问作者koque
相关产品推荐
相关产品推荐

