React中如何将API返回的Unix时间转为hh:mm用于Recharts图表
问题描述
我是React和API使用的新手,正在尝试使用Recharts制作图表,但遇到了问题:API返回的时间数据为Unix时间格式。以下是我的相关代码:
API数据获取代码
const [devices, setDevices] = useState([] as IDeviceData[]); useEffect(() => { fetch("http://api...") .then(response => { if (response.ok) { return response.json() } else if (response.status === 404) { return Promise.reject('Error 404') } else { return Promise.reject('There was an error: ' + response.status) } }) .then(data => setDevices(data)) .catch(error => navigate( `/sensors/${imei}/404-not-found/`, { state: { description: `No sensor found with: "${imei}"` } }, )); }, [imei, navigate, category]);
图表展示代码
<ResponsiveContainer width="100%" height="100%"> <LineChart data={devices} margin={{ top: 5, right: 20, bottom: 5, left: 0 }}> <Line type="monotone" dataKey={category} dot={{strokeWidth: '4'}} stroke="#0EA5E9" /> <CartesianGrid stroke="#ccc" strokeDasharray="5 5" /> <XAxis dataKey="timestamp"/> <YAxis /> <Tooltip /> </LineChart> </ResponsiveContainer>
已编写的时间戳转换函数
export function convertTimestampToDate(timestamp: string): string { return new Intl.DateTimeFormat('nl', { year: 'numeric', day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', }).format(parseInt(timestamp)); }
我不清楚如何在XAxis组件中使用存储在devices中的API数据并应用该转换函数,将Unix时间转为hh:mm格式。
解决方案
方法一:直接通过XAxis的tickFormatter格式化刻度
Recharts的XAxis组件支持tickFormatter属性,可直接传入你的转换函数,对每个时间戳进行格式化。修改XAxis代码如下:
<XAxis dataKey="timestamp" tickFormatter={(timestamp) => convertTimestampToDate(timestamp)} />
如果仅需要hh:mm格式,可调整转换函数的配置项:
export function convertTimestampToHHMM(timestamp: string): string { return new Intl.DateTimeFormat('nl', { hour: '2-digit', minute: '2-digit', }).format(parseInt(timestamp)); }
之后在tickFormatter中使用这个新函数即可。
方法二:获取数据时提前转换时间戳
若需要在多个场景使用格式化后的时间,可在API返回数据后先处理时间戳,再存入状态:
修改useEffect中的数据处理逻辑:
.then(data => { const formattedData = data.map(item => ({ ...item, formattedTime: convertTimestampToDate(item.timestamp) })); setDevices(formattedData); })
随后在XAxis中直接使用转换后的字段:
<XAxis dataKey="formattedTime" />
内容的提问来源于stack exchange,提问作者Ismail Yaman
相关产品推荐
相关产品推荐

