簡體   English   中英

如何打印 reactjs 中每個項目的所有評論列表的數量?

[英]How to print the number of all commented list for every project in reactjs?

我有主題列表(帖子)。 我想打印對每個主題 ID 的總評論數。 低於我嘗試過的

function Component() {
  const [comments, setComments] = useState([]);
  useEffect(() => {
    fetch(ApiUrlConstant.getApiFullUrl("https://jsonplaceholder.typicode.com/posts/"))
      .then(res => res.json())
      .then(json => setComments(json))
      .catch(() => setComments([]));
  }, []);
  //
  return <div>Comments: {comments.length}</div>;
}

以下是原鏈接https://jsonplaceholder.typicode.com/posts/1/comments

我認為問題在這里:

function Component() {

在這里,您使用了 function 名稱作為Component ,這是 React 中的保留關鍵字。 因此,將其更改為其他名稱,例如:

function MyComponent() {

並嘗試再次運行它。

除了用於清理的 function 之外,效果 function 不得返回任何內容。 您應該在效果中編寫異步 function 並立即調用它

您應該在內部使用 async function :

    useEffect(() => {
        async function fetchData() {
           const response = await fetch(ApiUrlConstant.getApiFullUrl("https://jsonplaceholder.typicode.com/posts/"))
           setComments(response)
        }
        fetchData();
      }, []);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM