使用 Intl.DateTimeFormat 根据 State 时区显示时间。
解读
在国内面试中,这道题表面考“国际化时间格式化”,实则同时考察 Redux 状态设计、不可变更新、Selector 性能优化、React-Redux 绑定以及浏览器 Intl API 的兼容性降级 五大维度。
面试官期望听到:
- 如何把“用户偏好时区”沉淀为 单一可信源(Single Source of Truth);
- 组件仅通过 mapStateToProps 或 useSelector 读取,不自行做时区运算;
- 当用户切换时区时,纯函数 Reducer 如何以不可变方式更新;
- 若浏览器不支持
Intl.DateTimeFormat(国内低端安卓、WebView 仍存),如何 兜底到 moment-timezone 或 dayjs 并保持一致性; - 时间显示组件必须 纯渲染,方便 Jest + @testing-library/react 做快照测试。
知识点
- 单一 Store 设计:
state.user.preference.timezone存 IANA 字符串(如Asia/Shanghai),而非偏移量,避免夏令时问题。 - 不可变更新:切换时区时必须返回新对象,禁止
state.user.preference.timezone = newZone。 - Selector 记忆化:使用 reselect 创建
makeGetFormattedTime工厂函数,把timezone + timestamp + locale作为缓存键,避免每次渲染都 new Intl.DateTimeFormat。 - React-Redux 绑定:类组件用
connect+mapStateToProps,函数组件用useSelector;必须 shallowEqual 比较 props,防止格式化函数引用变化导致重渲染。 - Intl 降级:若
typeof Intl === 'undefined' || !Intl.DateTimeFormat.prototype.formatToParts,走 polyfill 或服务端预计算,但 Redux 里仍保存 IANA 字符串,保持逻辑统一。 - 时区与国际化分离:Redux 只负责“原始数据 + 用户偏好”,不保存任何格式化后的字符串,确保切换语言包(zh-CN ↔ en-US)也能即时响应。
答案
- State 结构
{
user: {
preference: {
timezone: 'Asia/Shanghai', // IANA
locale: 'zh-CN'
}
},
entities: {
articles: [
{ id: 1, publishAt: 1710000000000 } // 毫秒时间戳
]
}
}
- Action
export const changeTimezone = (zone) => ({
type: 'USER_PREFERENCE_TIMEZONE_CHANGE',
payload: zone
});
- Reducer(不可变)
const preferenceReducer = (state = initialPref, action) => {
switch (action.type) {
case 'USER_PREFERENCE_TIMEZONE_CHANGE':
return { ...state, timezone: action.payload };
default:
return state;
}
};
- Selector(带记忆化)
import { createSelector } from 'reselect';
const getTimezone = state => state.user.preference.timezone;
const getLocale = state => state.user.preference.locale;
const getTimestamp = (_, props) => props.ts;
export const makeGetFormattedTime = () =>
createSelector(
[getTimezone, getLocale, getTimestamp],
(zone, locale, ts) => {
try {
return new Intl.DateTimeFormat(locale, {
timeZone: zone,
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit'
}).format(new Date(ts));
} catch (e) {
// 降级:服务端已注入的 dayjs 时区数据
return window.dayjs.tz(ts, zone).locale(locale).format('YYYY-MM-DD HH:mm:ss');
}
}
);
- 组件(函数组件示例)
import React from 'react';
import { useSelector } from 'react-redux';
import { makeGetFormattedTime } from '../selectors/time';
const ArticleTime = ({ ts }) => {
const selector = React.useMemo(makeGetFormattedTime, []);
const formatted = useSelector(state => selector(state, { ts }));
return <time>{formatted}</time>;
};
- 测试(Jest)
it('根据 Redux 时区格式化时间', () => {
const store = mockStore({
user: { preference: { timezone: 'America/New_York', locale: 'en-US' } }
});
const { container } = render(
<Provider store={store}>
<ArticleTime ts={1710000000000} />
</Provider>
);
expect(container.textContent).toMatch(/03\/09\/2024.*02:40:00 PM/);
});
拓展思考
- 服务端渲染(SSR)与 hydration:Node 端同样使用
Intl.DateTimeFormat,但需保证 时区数据版本与浏览器一致,否则会出现 checksum 不匹配;可在构建阶段把tzdata打入 bundle。 - 大数据量列表优化:若一次渲染 500 条时间,逐行 new Intl.DateTimeFormat 会成为热点,可在 selector 层做 LRU 缓存,以
locale+timezone+formatOptions为 key 复用实例。 - 用户偏好持久化:把
preference切片序列化到localStorage,但加载时需 校验 IANA 字符串合法性,防止用户手动篡改导致后续Intl抛错。 - 跨项目复用:将“时区 + 格式化”封装成 @company/redux-intl-utils,对外暴露高阶组件
withTime(Component),内部自动注入formattedTimeprop,实现 业务组件零感知。