如何对 Store 中的手机号做掩码处理?
解读
面试官真正想考察的是:
- 你是否理解 Redux 数据流是单向、纯函数驱动 的,掩码属于 派生数据,不能污染原始 State;
- 在国内场景下,手机号属于 敏感个人信息,必须 脱敏展示 且 不脱库;
- 你能否在 不破坏时间旅行调试、不增加冗余 State 的前提下,给出 可维护、可测试 的完整方案;
- 是否熟悉 reselect、useSelector 性能优化 以及 SSR 安全 等工程细节。
一句话:把“掩码”做成 派生值,而不是 存储值,并保证 中国手机号 11 位、中间 4 位星号 的合规脱敏。
知识点
- 单一 Store 原则:原始手机号只能存一份,掩码不能写回。
- 纯函数 Reducer:禁止在 reducer 里做掩码,否则破坏可预测性。
- reselect 库:创建 记忆化 Selector,把“原始手机号→掩码”做成 派生数据,避免重复计算。
- react-redux:通过 useSelector 订阅派生值,组件无感知。
- 中国手机号规则:1xx xxxx xxxx,脱敏后 1xx****xxxx,正则 /^(\d{3})\d{4}(\d{4})$/。
- 性能与安全:
– 记忆化防止每次 render 都生成新字符串;
– SSR 时只在服务端注入脱敏值,防止源码泄露;
– 单元测试 只需断言 selector 输入输出,无需 mock Store。
答案
-
State 设计
const initialState = { profile: { mobile: '13812345678' // 只存原始号 } }; -
创建记忆化 Selector(reselect)
import { createSelector } from 'reselect'; const getMobile = state => state.profile.mobile; export const getMaskedMobile = createSelector( [getMobile], mobile => mobile ? mobile.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') : '' ); -
组件使用
import { useSelector } from 'react-redux'; import { getMaskedMobile } from '../selectors'; function MobileCell() { const masked = useSelector(getMaskedMobile); return <span>{masked}</span>; } -
测试用例(jest)
test('手机号脱敏', () => { const state = { profile: { mobile: '19900001111' } }; expect(getMaskedMobile(state)).toBe('199****1111'); }); -
禁止事项
- 绝不把掩码值再 dispatch 回 Store;
- 不在 reducer、effect 中做字符串替换;
- 不在组件内手写
mobile.slice,统一走 selector,方便后续 规则升级(如海外号码)。
拓展思考
- 动态脱敏策略:若后台返回脱敏级别(0 不脱、1 半脱、2 全脱),可在 selector 里再读
state.system.maskLevel,同一数据源,多套派生视图,无需改 State。 - 跨端安全:在 React Native 里,防止 调试面板 直接看到原始 mobile,可在 production 环境 把
getMobileselector 替换为 抛错版本,彻底阻断非法读取。 - 分页列表场景:订单列表 20 条手机号都需脱敏,使用 reselect 的 mapMemoize 做批量记忆,避免 20 次重复正则。
- 时间旅行调试:记录 action 时只存原始号,调试器回放时 自动应用当前 selector 规则,保证 脱敏逻辑与业务逻辑解耦,可随时 回滚到旧版本脱敏策略 而无需改历史数据。