簡體   English   中英

如何在反應中獲取嵌套數據

[英]How to fetch nested data in react

關於在反應中獲取嵌套數據的問題。

蜜蜂

  1. https://jsonplaceholder.typicode.com/posts
  2. https://jsonplaceholder.typicode.com/posts/${postId}/comments

能夠獲取帖子列表。 現在想從點擊帖子時獲取評論列表

這是到目前為止的代碼

import React, { useEffect, useState } from "react";
import Post from "./Post";

const [posts, setPosts] = useState([]);
const [comments, setComments] = useState([]);

function App() {
  const [posts, setPosts] = useState([]);
  const [comments, setComments] = useState([]);

useEffect(() => {
  const loadposts = async() => {
    const resp = await fetch("https://jsonplaceholder.typicode.com/posts?userId=1");
    const data = await resp.json();
    setPosts(data);
  }
  loadposts();
}, []);

return (
  <div className="App">
    <ul>
      {posts.map((post) => 
      (
        <div>
          <li key={post.id}>
            <Post 
            userId={post.id}
            title={post.title} 
            body={post.body} 
            />
          </li>
      </div>
      ))
      }
    </ul>
  </div>
);
}

export default App;

function Post({title, body, postId}) {
  
  return (
      <div>
          <h5>{postId}</h5>
          <h1>{title}</h1>
          <p>{body}</p>
      </div>
  )
}

export default Post

感謝任何幫助。 謝謝

首先,“/posts”端點返回用戶的帖子,因此查詢“/posts?userId=1”將返回用戶 id 為1的所有帖子。 您錯誤地將userId道具傳遞給Post組件,而不是特定帖子的id ,即

<Post userId={post.id} title={post.title}  body={post.body} />

React 鍵也應該放在被映射的最外層元素上,在你的例子中是div ,但是由於li已經是一個塊級元素,所以div基本上是無關的。

<ul>
  {posts.map((post) => (
    <li key={post.id}> // <-- remove div and place React key on li
      <Post
        postId={post.id} // <-- pass the post's id
        title={post.title}
        body={post.body}
      />
    </li>
  ))}
</ul>

Post組件中創建一個獲取評論實用程序和單擊處理程序,並將單擊處理程序附加到標題 header。 有條件地呈現評論。 如果還不清楚,您會將comments state 移動到Posts中,以便每個帖子組件維護自己的副本。 以下是渲染獲取評論的示例,您可以使用您選擇的任何條件渲染和字段子集。

const fetchComments = async (postId) => {
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/posts/${postId}/comments`
  );
  return response.json();
};

function Post({ title, body, postId }) {
  const [comments, setComments] = useState([]);

  const clickHandler = () => {
    fetchComments(postId).then(setComments);
  };

  return (
    <div>
      <h5>{postId}</h5>
      <h1 onClick={clickHandler}>{title}</h1>
      <p>{body}</p>
      {comments.length && (
        <>
          Comments:
          <ul>
            {comments.map(({ id, email, name, body }) => (
              <li key={id}>
                <dl>
                  <dt>{email} - {name}</dt>
                  <dd>{body}</dd>
                </dl>
              </li>
            ))}
          </ul>
        </>
      )}
    </div>
  );
}

編輯如何在反應中獲取嵌套數據

如果有人在尋找工作解決方案


function Post() {
const {id} = useParams();
const [comments, setComments] = useState([]);

useEffect(() => {
    fetch(`https://jsonplaceholder.typicode.com/posts/${id}/comments`)
    .then((res) => res.json())
    .then(setComments)
    .catch((error) => {
        console.log(error)
    })
    console.log("setComments: ", setComments)
}, [])

    return (
        <div>
            {comments && comments.map((comment) => (
                <div key={comment.id}>
                    <p>{comment.body}</p>
                </div>

            ))}

        </div>
    )
}
export default Post

then update rendering 

    <div className="App">
      <Switch>
     <Route exact path='/'>
        {posts.map((post) => (
         <article key={post.id}> 
          <h1>{post.title}</h1>
            <Link to ={`/${post.id}`}>
              <p>{post.body}</p>
            </Link>
       </article>
      ))}
   </Route>

     <Route path ='/:id'>
        <Post/>
     </Route>
   </Switch>

  </div>

   

    
  

暫無
暫無

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

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