素胚勾勒不出你
2023-03-03 16:06:09
我有一個(gè) React 組件,它呈現(xiàn)正在映射的項(xiàng)目列表,并顯示每個(gè)項(xiàng)目的 ID。當(dāng)組件首次加載時(shí),列表項(xiàng)出現(xiàn),但一兩秒鐘后消失,并在控制臺(tái)中返回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> </> )}并且控制臺(tái)顯示:我在該組件上方注釋掉了很多代碼,因此控制臺(tái)中的行指的是console.log(post.id);.有誰(shuí)知道可能是什么原因造成的?
1 回答

呼如林
TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超3個(gè)贊
不需要此 useEffect。兩個(gè) useEffects 都在初始加載時(shí)嘗試使用相同的 url 參數(shù)訪問(wèn)相同的端點(diǎn)。
useEffect(() => {
if (categoryId) {
fetch(state.source.api + "/wp/v2/posts?categories=" + categoryId + "&per_page=5")
.then((response) => response.json())
.then((data) => {
setPosts(data);
});
}
}, [categoryId]);
而且我認(rèn)為數(shù)組在這里沒(méi)有正確合并:
try to replace:
setPosts([...posts, data]);
to:
setPosts([...posts, ...data]);
添加回答
舉報(bào)
0/150
提交
取消