You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为学生成绩数组编写Angular NGRX状态与Reducer方法

NGRX学生成绩状态与Reducer实现

原始学生成绩JSON结构

{
  "John": [
    {
      "physics": "55"
    },
    {
      "chemistry": "88"
    },
    {
      "social": "90"
    }
  ],
  "James": [
    {
      "physics": "55"
    },
    {
      "chemistry": "45"
    }
  ]
}

对应NGRX状态定义

export interface Score {
  physics: string;
  chemistry: string;
  social: string;
}

export interface IScoreState {
  [studentName: string]: Score;
}

注:原JSON中James无social成绩,若要贴合原始数据,建议将Score的属性设为可选类型,避免冗余的空值填充:

export interface Score {
  physics?: string;
  chemistry?: string;
  social?: string;
}

核心Action定义

Reducer需通过Action触发,先定义对应的Action:

import { createAction, props } from '@ngrx/store';

// 新增学生条目
export const addStudent = createAction(
  '[Score] Add Student',
  props<{ studentName: string; scores: Score }>()
);

// 更新学生成绩
export const updateStudentScore = createAction(
  '[Score] Update Student Score',
  props<{ studentName: string; updatedScores: Partial<Score> }>()
);

分场景实现Reducer

场景1:新增学生条目(添加Peter,三科成绩均为35)

基于初始状态创建新状态,添加指定学生的完整成绩信息:

import { createReducer, on } from '@ngrx/store';
import { addStudent, updateStudentScore } from './score.actions';

// 初始状态(转换原始JSON得到)
const initialState: IScoreState = {
  John: { physics: '55', chemistry: '88', social: '90' },
  James: { physics: '55', chemistry: '45', social: '' } // 若Score属性为可选,此处可省略social字段
};

export const scoreReducer = createReducer(
  initialState,
  // 处理新增学生逻辑
  on(addStudent, (state, { studentName, scores }) => ({
    ...state,
    [studentName]: scores
  }))
);

触发方式:

// 触发添加Peter的Action
store.dispatch(addStudent({
  studentName: 'Peter',
  scores: { physics: '35', chemistry: '35', social: '35' }
}));

场景2:更新已有学生成绩(为Peter补充social科目成绩45)

在原有学生成绩基础上,合并更新指定科目数据:

// 完善scoreReducer,添加成绩更新逻辑
export const scoreReducer = createReducer(
  initialState,
  on(addStudent, (state, { studentName, scores }) => ({
    ...state,
    [studentName]: scores
  })),
  // 处理成绩更新逻辑
  on(updateStudentScore, (state, { studentName, updatedScores }) => ({
    ...state,
    [studentName]: {
      ...state[studentName],
      ...updatedScores
    }
  }))
);

触发方式:

// 触发更新Peter的social成绩的Action
store.dispatch(updateStudentScore({
  studentName: 'Peter',
  updatedScores: { social: '45' }
}));

内容的提问来源于stack exchange,提问作者user2132124

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 14:06:55