用 normalizr 把嵌套文章数据打平,并写出 selector。
解读
国内一线团队(阿里、美团、字节等)在 Redux 项目里普遍要求“数据先扁平化再进 Store”,normalizr 是官方推荐的打平利器。面试官想一次性验证三件事:
- 你能否把嵌套 JSON 一键拍平成实体表,避免深层拷贝;
- 你能否反向还原视图需要的数据形状,即 selector 写法;
- 你能否兼顾性能与可维护性(memoization、reselect、immutable 更新)。
如果只说“我会用 normalizr”却写不出 schema、给不出 selector,基本会被判“只听过没用过”。
知识点
- normalizr 三件套:schema.Entity、schema.Array、normalize;
- Redux Store 约定:顶层按实体名分片,存 byId 与 allIds,保证 O(1) 查询;
- selector 职责:把扁平状态还原成组件想要的“嵌套”形状,同时做 memo;
- reselect 的 createSelector:默认做浅比较缓存,避免重复计算;
- 国内代码审查红线:禁止在 selector 里做 new Date()、Math.random() 等副作用,防止时间旅行调试失效。
答案
- 定义 schema(Article.js)
import { schema, normalize } from 'normalizr';
// 用户实体
const user = new schema.Entity('users');
// 评论实体,递归引用自身
const comment = new schema.Entity('comments', {
author: user,
replies: [new schema.Entity('comments')] // 自引用
});
// 文章实体
const article = new schema.Entity('articles', {
author: user,
comments: [comment]
});
export { article, comment, user };
- 服务端原始嵌套数据
const raw = {
id: 1,
title: 'Redux 性能优化',
author: { id: 101, name: '王工' },
comments: [
{
id: 201,
content: '好文',
author: { id: 102, name: '李产品' },
replies: [
{ id: 202, content: '+1', author: { id: 103, name: '陈测试' }, replies: [] }
]
}
]
};
- 打平并入库
import { normalize } from 'normalizr';
import { article } from './Article';
const { entities, result } = normalize(raw, article);
// 国内常规写法:直接塞进对应 slice
dispatch({
type: 'BATCH_UPDATE_ENTITIES',
payload: {
articles: entities.articles,
users: entities.users,
comments: entities.comments,
result // 存根 id,方便快速拿到“当前文章”
}
});
- Redux state 形状
state = {
entities: {
articles: { byId: {}, allIds: [] },
users: { byId: {}, allIds: [] },
comments: { byId: {}, allIds: [] }
},
ui: { currentArticleId: 1 }
};
- selector(支持 memo,支持深度还原 replies)
import { createSelector } from 'reselect';
const getEntities = state => state.entities;
const getCurrentId = state => state.ui.currentArticleId;
// 工具:递归把评论 id 列表还原成树
const denormalizeComments = (ids, entities) =>
ids.map(id => {
const c = entities.comments.byId[id];
return {
...c,
author: entities.users.byId[c.author],
replies: denormalizeComments(c.replies || [], entities)
};
});
export const selectCurrentArticle = createSelector(
[getEntities, getCurrentId],
(entities, id) => {
if (!id) return null;
const art = entities.articles.byId[id];
if (!art) return null;
return {
...art,
author: entities.users.byId[art.author],
comments: denormalizeComments(art.comments, entities)
};
}
);
- 组件内使用
const article = useSelector(selectCurrentArticle);
至此,数据流单向、形状可预测、selector 带缓存,完全符合国内大厂工程规范。
拓展思考
- 分页场景:如果评论分页,可把 allIds 换成 pageIds 数组,selector 按页码切片,避免一次性还原上千条;
- 增量更新:后台推送新评论时,只发“增量实体”,selector 因浅比较会复用 99% 的旧缓存,渲染性能翻倍;
- TypeScript 加持:给 Entity 写泛型接口,配合
@reduxjs/toolkit的createEntityAdapter,10 分钟就能搭出类型安全的 CRUD; - 替代方案:GraphQL + Relay 也能自动打平,但在国内存量 Redux 项目里,normalizr 仍是 ROI 最高的轻量方案,无需替换整栈。