我有一個(gè)組件可以對(duì)博客文章執(zhí)行分頁(yè)功能。每次單擊“加載更多”按鈕時(shí),頁(yè)面底部都會(huì)加載另外五個(gè)帖子。不過,我現(xiàn)在對(duì)如何解決問題一無所知。問題:?jiǎn)螕簟凹虞d更多”按鈕并且所有可用帖子都可見后,“加載更多”按鈕應(yīng)該消失。代碼:const Posts = ({ state }) => { const [categories, setCategories] = useState([]); const [categoryId, setCategoryId] = useState(); const [page, setPage] = useState(1); const [posts, setPosts] = useState([]); // Posts for each category const [allPosts, setAllPosts] = useState([]); // All posts from all categories // Get all of the available categories useEffect(() => { fetch(state.source.api + "/wp/v2/categories") .then(response => response.json()) .then(data => { setCategories(data); }) }, []); useEffect(() => { if (categoryId) { fetch(state.source.api + "/wp/v2/posts?categories=" + categoryId + "&per_page=5") .then((response) => response.json()) .then((data) => { setPosts(data); }); } }, [categoryId]); // Get posts for each category useEffect(() => { if (!categoryId) { return; } let url = state.source.api + "/wp/v2/posts?categories=" + categoryId + "&per_page=5"; if (page > 1) { url += `&page=${page}`; } fetch(url) .then((response) => response.json()) .then((data) => { setPosts([...posts, ...data]); }); }, [categoryId, page]); useEffect(() => { let url = state.source.api + "/wp/v2/posts?per_page=5"; if (page > 1) { url += `&page=${page}`; } fetch(url) .then((response) => response.json()) .then((data) => { setAllPosts([...allPosts, ...data]); }); }假設(shè)最多有 3 頁(yè)的帖子,一次查看 5 個(gè) - 所以總共 15 個(gè)帖子......一旦所有 3 頁(yè)都可見,我再次點(diǎn)擊“加載更多”(即使沒有更多帖子可用) ,我收到一個(gè)控制臺(tái)錯(cuò)誤... my api... GET /wp/v2/posts?categories=78&per_page=5&page=4 400 (Bad Request),這顯然意味著沒有要獲取的第 4 頁(yè),因?yàn)闆]有更多帖子。我認(rèn)為這需要一個(gè) if 語(yǔ)句,但我不確定我將如何開始編寫它。有人有任何意見嗎?
在 React 中有條件地顯示按鈕
幕布斯7119047
2023-03-03 13:09:54