post 在 React 挂钩中单击不会显示详细信息

post detail doesn't show by click in react hooks

当我单击每个 post 项目时,详细信息不会显示在浏览器上(post.js 组件用于显示每个 post 项目的详细信息)。浏览器上唯一显示的是白页! .这些是我的组件:

感谢您的帮助。

这是我的 App.js 组件:

import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./components/Home";
import About from "./components/About";
import Contact from "./components/Contact";
import Post from "./components/Post";

const App = () => {
  return (
    <BrowserRouter>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home/>}></Route>
        <Route path="about" element={<About/> }></Route>
        <Route path="contact" element={<Contact/>}></Route>
        <Route path="/posts/:id" element={<Post/>}></Route>
      </Routes>
    </BrowserRouter>
  );
};

export default App;

Home.js分量:

import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";

const Home = () => {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((response) => response.json())
      .then((data) => {
        setPosts(data.slice(0, 10));
      });
  }, []);
  return (
    <div className="container">
      <h4 className="center">Home</h4>
      {posts.map((post) => (
        <div className="post card" key={post.id}>
          <div className="card-content">
            <Link to={`/posts/${post.id}`}>
              <span className="card-title">{post.title}</span>
            </Link>
            <p>{post.body}</p>
          </div>
        </div>
      ))}
    </div>
  );
};

export default Home;

Post.js 组件,用于通过单击显示每个 post 项目的详细信息:

import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";

const Post = () => {
  const { id } = useParams();
  const [post, setPost ]= useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(
        `https://jsonplaceholder.typicode.com/posts/${id}`
      );
      const newData = await response.json();
      setPost(newData);
    };
    fetchData();
  }, [id]);

  return (
    <div>
      <p>{post.title}</p>
       <p>{post.body}</p>
    </div>
  );
};

export default Post;

据我所知并重现,当 Post 试图在填充 post 状态之前在初始渲染上渲染 post.title 时,您的代码会抛出错误。初始 post 状态值为 null,您无法访问 null 或未定义值的属性。

您应该有条件地呈现 post 状态。

示例:

return post ? (
  <div>
    <p>{post.title}</p>
    <p>{post.body}</p>
  </div>
) : null; // or some loading indicator, etc...