import React, { useEffect, useState } from 'react'; import { Link } from 'react-router-dom'; import { getArchive, listPosts } from '../api/blog.js'; /** 归档页(路由 /archive.html): * archive API 只返回 {month, count},无按月文章列表接口; * 列表接口 /blog/posts 无分页返回全部已发布文章(文章量小), * 前端按 created_at 客户端分组,配合 archive API 的月份与计数展示。 */ export default function Archive() { const [months, setMonths] = useState([]); // [{month, count, posts:[]}] const [loading, setLoading] = useState(true); const [error, setError] = useState(''); useEffect(() => { Promise.all([getArchive(), listPosts()]) .then(([arc, posts]) => { const byMonth = new Map(); (posts || []).forEach((p) => { const m = (p.created_at || '').slice(0, 7); // YYYY-MM if (!m) return; if (!byMonth.has(m)) byMonth.set(m, []); byMonth.get(m).push(p); }); // 以 archive API 的月份顺序为准(desc),count 以实际分组统计为准 const countMap = new Map(); (arc || []).forEach((a) => countMap.set(a.month, a.count)); const list = Array.from(byMonth.entries()).map(([month, ps]) => ({ month, count: ps.length, posts: ps, })); // 补齐 archive 里有、分组里没有的月份(理论上不会出现) (arc || []).forEach((a) => { if (!byMonth.has(a.month)) list.push({ month: a.month, count: a.count, posts: [] }); }); list.sort((a, b) => (a.month < b.month ? 1 : -1)); setMonths(list); }) .catch((e) => setError(e.message || '加载失败')) .finally(() => setLoading(false)); }, []); const fmtMonth = (m) => { const [y, mm] = m.split('-'); return `${y}年${mm}月`; }; return (
{error}
暂无文章
暂无文章
) : ( m.posts.map((p) => ( {p.title} {(p.created_at || '').slice(0, 10)} )) )}