fix: append new trades to bottom instead of top, fixed container height to prevent page jump

This commit is contained in:
root 2026-02-27 12:51:36 +00:00
parent 2a6fb97a43
commit 1db9e55259

View File

@ -56,19 +56,29 @@ function timeStr(ms: number) {
function LiveTrades({ symbol }: { symbol: Symbol }) { function LiveTrades({ symbol }: { symbol: Symbol }) {
const [trades, setTrades] = useState<TradeRow[]>([]); const [trades, setTrades] = useState<TradeRow[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const containerRef = useRef<HTMLDivElement>(null);
const lastAggId = useRef<number>(0);
useEffect(() => { useEffect(() => {
let running = true; let running = true;
// 重置
setTrades([]);
setLoading(true);
lastAggId.current = 0;
const fetch = async () => { const fetch = async () => {
try { try {
const res = await authFetch(`/api/trades/latest?symbol=${symbol}&limit=30`); const res = await authFetch(`/api/trades/latest?symbol=${symbol}&limit=30`);
if (!res.ok) return; if (!res.ok) return;
const data = await res.json(); const data = await res.json();
if (!running) return; if (!running) return;
const incoming: TradeRow[] = (data.data || []).reverse(); // 改为时间升序
setTrades(prev => { setTrades(prev => {
const existingIds = new Set(prev.map((t: TradeRow) => t.agg_id)); const existingIds = new Set(prev.map((t: TradeRow) => t.agg_id));
const newOnes = (data.data || []).filter((t: TradeRow) => !existingIds.has(t.agg_id)); const newOnes = incoming.filter((t: TradeRow) => !existingIds.has(t.agg_id));
return [...newOnes, ...prev].slice(0, 60); if (newOnes.length === 0) return prev;
// 追加到末尾保持时间升序最多保留120条
return [...prev, ...newOnes].slice(-120);
}); });
setLoading(false); setLoading(false);
} catch {} } catch {}
@ -93,7 +103,7 @@ function LiveTrades({ symbol }: { symbol: Symbol }) {
<span className="text-red-500 font-medium"> </span>= <span className="text-red-500 font-medium"> </span>=
</p> </p>
</div> </div>
<div className="overflow-y-auto flex-1" style={{ maxHeight: 420, scrollBehavior: "auto" }}> <div ref={containerRef} className="overflow-y-auto flex-1" style={{ height: 420 }}>
{loading ? ( {loading ? (
<div className="flex items-center justify-center h-24 text-slate-400 text-sm">...</div> <div className="flex items-center justify-center h-24 text-slate-400 text-sm">...</div>
) : ( ) : (