This commit is contained in:
Developer
2026-03-16 14:24:32 +08:00
parent 9a70dd0c4d
commit 47d2e8479e
8 changed files with 316 additions and 97 deletions

View File

@@ -1,30 +1,49 @@
import { useState, useCallback, useRef } from 'react';
import { useState, useCallback, useRef, useEffect } from 'react';
import { getComments } from '../services/bilibili';
import type { Comment } from '../services/types';
export function useComments(aid: number) {
export function useComments(aid: number, sort: number) {
const [comments, setComments] = useState<Comment[]>([]);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
const pageRef = useRef(1);
const loadingRef = useRef(false);
const hasMoreRef = useRef(true);
const sortRef = useRef(sort);
const aidRef = useRef(aid);
const cursorRef = useRef(''); // empty = first page
aidRef.current = aid;
useEffect(() => {
if (sortRef.current === sort) return;
sortRef.current = sort;
cursorRef.current = '';
hasMoreRef.current = true;
setComments([]);
setHasMore(true);
}, [sort]);
const load = useCallback(async () => {
if (loadingRef.current || !hasMore || !aid) return;
if (loadingRef.current || !hasMoreRef.current || !aidRef.current) return;
loadingRef.current = true;
setLoading(true);
try {
const data = await getComments(aid, pageRef.current);
if (data.length === 0) { setHasMore(false); return; }
setComments(prev => [...prev, ...data]);
pageRef.current += 1;
const isFirstPage = cursorRef.current === '';
const { replies, nextCursor, isEnd } = await getComments(aidRef.current, cursorRef.current, sortRef.current);
cursorRef.current = nextCursor;
setComments(prev => isFirstPage ? replies : [...prev, ...replies]);
if (isEnd || replies.length === 0) {
hasMoreRef.current = false;
setHasMore(false);
}
} catch (e) {
console.error('Failed to load comments', e);
} finally {
loadingRef.current = false;
setLoading(false);
}
}, [aid, hasMore]);
}, []);
return { comments, loading, hasMore, load };
}