第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

React 組件返回映射項(xiàng)列表,然后消失

React 組件返回映射項(xiàng)列表,然后消失

素胚勾勒不出你 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]);


查看完整回答
反對(duì) 回復(fù) 2023-03-03
  • 1 回答
  • 0 關(guān)注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)