我有一個 React 組件,它呈現正在映射的項目列表,并顯示每個項目的 ID。當組件首次加載時,列表項出現,但一兩秒鐘后消失,并在控制臺中返回undefined。正在渲染的組件是:const Posts = ({ state }) => { const [categories, setCategories] = useState([]); const [categoryId, setCategoryId] = useState(); const [page, setPage] = useState(1); const [posts, setPosts] = useState([]); 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]); 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]); return ( <> {categories.length > 0 ? ( categories.map((category, i) => { return ( <button key={i} onClick={() => setCategoryId(category.id)}>{category.name}</button> ) }) ) : ( <p>Loading...</p> ) } <div> {posts.length === 0 ? ( <p>No posts...</p> ) : ( <> <ol> {posts.map((post, i) => { console.log(post.id); return ( <li key={i}>{post.id}</li> ) })} </ol> <button onClick={() => { setPage(page + 1); }}>Load more</button> </> )} </div> </> )}并且控制臺顯示:我在該組件上方注釋掉了很多代碼,因此控制臺中的行指的是console.log(post.id);.有誰知道可能是什么原因造成的?
React 組件返回映射項列表,然后消失
素胚勾勒不出你
2023-03-03 16:06:09