写出自增排序的 addOne、upsertOne、removeAll 组合用例。
解读
面试官真正想考察的是:
- 你是否理解 不可变 State 与 纯函数 Reducer 的写法;
- 能否在 单一 Store 里把“自增主键”与“排序”这两个业务需求落地;
- 对 Redux Toolkit(RTK)的
createSlice是否熟悉——国内一线团队 90% 已默认用 RTK,手写switch...case会被直接判为“历史代码”; - 组合用例必须覆盖 addOne(新增并自增 id)、upsertOne(存在则更新,不存在则新增,同样保证 id 自增)、removeAll(清空列表并重置自增种子)三个动作,且 State 始终保持 升序排列。
知识点
- createSlice + PayloadAction:官方推荐写法,减少样板代码;
- Entity + sort 字段分离:用
ids: number[]保存排序后的 id 序列,entities: Record<number, Entity>保存实体映射,符合国内“标准化状态”实践; - 自增主键:在 slice 外维护一个闭包
let nextId = 1,保证每次生成唯一 id; - 不可变更新:用
array.sort前先做slice()复制,避免 mutate 原数组; - upsert 语义:先查
entities[action.payload.id],存在则合并,不存在则分配新 id; - removeAll:既要清空
ids与entities,也要把nextId重置为 1,防止下次 add 出现“历史断层”; - 单元测试:国内面试常追问“怎么测”,需保证每个 case 都返回全新引用。
答案
// models.ts
export interface Item {
id: number
name: string
price: number
}
// 闭包自增器
let nextId = 1
// slice.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import type { Item } from './models'
interface ItemsState {
ids: number[] // 升序排序后的 id 列表
entities: Record<number, Item>
}
const initialState: ItemsState = {
ids: [],
entities: {}
}
const itemsSlice = createSlice({
name: 'items',
initialState,
reducers: {
// 1. 新增一条,自动分配自增 id,并重新排序
addOne(state, action: PayloadAction<Omit<Item, 'id'>>) {
const newItem: Item = { ...action.payload, id: nextId++ }
state.entities[newItem.id] = newItem
state.ids = state.ids.concat(newItem.id).slice().sort((a, b) => a - b)
},
// 2. 存在则更新,不存在则新增,同样保证排序
upsertOne(state, action: PayloadAction<Item>) {
const { id } = action.payload
// 不存在 -> 新增
if (!state.entities[id]) {
state.entities[id] = action.payload
state.ids = state.ids.concat(id).slice().sort((a, b) => a - b)
} else {
// 存在 -> 合并更新
state.entities[id] = { ...state.entities[id], ...action.payload }
// id 已存在,顺序不变,无需重排
}
},
// 3. 清空并重置自增种子
removeAll(state) {
state.ids = []
state.entities = {}
nextId = 1
}
}
})
export const { addOne, upsertOne, removeAll } = itemsSlice.actions
export default itemsSlice.reducer
组合用例(可直接贴进 Jest 文件,国内面试现场常要求手写):
import reducer, { addOne, upsertOne, removeAll } from './slice'
describe('自增排序组合用例', () => {
it('addOne -> upsertOne -> removeAll 流程', () => {
let state = reducer(undefined, { type: '' })
// 1. addOne 两条
state = reducer(state, addOne({ name: '苹果', price: 5 }))
state = reducer(state, addOne({ name: '香蕉', price: 3 }))
expect(state.ids).toEqual([1, 2])
expect(state.entities[2].name).toBe('香蕉')
// 2. upsertOne 已存在 id=1,更新价格
state = reducer(state, upsertOne({ id: 1, name: '苹果', price: 6 }))
expect(state.entities[1].price).toBe(6)
expect(state.ids).toEqual([1, 2]) // 顺序不变
// 3. upsertOne 不存在 id=3,新增
state = reducer(state, upsertOne({ id: 3, name: '橙子', price: 4 }))
expect(state.ids).toEqual([1, 2, 3])
// 4. removeAll 清空
state = reducer(state, removeAll())
expect(state.ids).toEqual([])
expect(state.entities).toEqual({})
// 5. 再次 addOne,id 从 1 重新开始
state = reducer(state, addOne({ name: '重置商品', price: 0 }))
expect(state.ids).toEqual([1])
})
})
拓展思考
- 并发场景:如果未来做“服务端自增”,需要把
nextId逻辑移到后端或 UUID,避免分布式冲突; - 分页与排序:当数据量上万条,前端全量排序会卡顿,可改为“后端排序 + 分页加载”,Redux 只存当前页;
- normalizr 与实体适配器:RTK 提供
createEntityAdapter,内置addOne、upsertOne、removeAll并自动维护排序,可进一步压缩代码; - 时间旅行调试:保持 State 不可变后,可直接使用 Redux DevTools 回放,现场演示该功能是国内加分项;
- TypeScript 严格模式:把
nextId封装进slice的prepare回调,避免全局变量污染,同时让类型推导更严谨。