亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

React 組件返回映射項列表,然后消失

React 組件返回映射項列表,然后消失

素胚勾勒不出你 2023-03-03 16:06:09
我有一個 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);.有誰知道可能是什么原因造成的?
查看完整描述

1 回答

?
呼如林

TA貢獻1798條經驗 獲得超3個贊

不需要此 useEffect。兩個 useEffects 都在初始加載時嘗試使用相同的 url 參數訪問相同的端點。


 useEffect(() => {

    if (categoryId) {

      fetch(state.source.api + "/wp/v2/posts?categories=" + categoryId + "&per_page=5")

        .then((response) => response.json())

        .then((data) => {

          setPosts(data);

        });

    }

  }, [categoryId]);

而且我認為數組在這里沒有正確合并:


try to replace:

setPosts([...posts, data]);


to:

setPosts([...posts, ...data]);


查看完整回答
反對 回復 2023-03-03
  • 1 回答
  • 0 關注
  • 169 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號