reactjs React-JS单次访视后不工作|没有与位置“/posts/1”匹配的路由

chhqkbe1  于 2023-01-08  发布在  React
关注(0)|答案(1)|浏览(129)

我想使一个博客网站的单一博客页面阅读,但它不工作
我需要有人帮我解决这个错误。
App.js

import Demo from "./components/Pages/Demo/Demo";
import DemoPost from "./components/Pages/Demo/Post";

function App() {
  return (
    <div>
      <Routes>
        <Route path='/posts' exact element={<Demo />} />
        <Route path='/demo/:pid' element={<DemoPost />} />
      </Routes>
    </div>
  );
}

export default App;

Posts.js

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

function Demo() {
   const [posts, setPosts] = useState([]);

   useEffect(() => {
      fetch('https://jsonplaceholder.typicode.com/posts')
         .then(response => response.json())
         .then(json => setPosts(json))
   }, []);

   return (
      <div className="posts">
         <div className="grid">

            {posts.map(post => (
               <div key={post.id}>
                  <Link to={`/posts/${post.id}`}>
                     <h2>{post.title}</h2>
                     <p>{post.body}</p>
                  </Link>
               </div>
            ))}
         </div>
      </div>
   )
}
export default Demo

Post.js

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

function Post({ match }) {
   const [post, setPost] = useState([]);

   useEffect(() => {
      fetch(`https://jsonplaceholder.typicode.com/posts${match.params.pid}`)
         .then(response => response.json())
         .then(json => setPost(json))

      console.log(match, 'why not show match');

   }, []);

   return (
      <div className="posts">
         <div className="post-container">
            <h1>{post.title}</h1>
            <p>{post.body}</p>
         </div>
      </div>
   )
}

export default Post
mzsu5hc0

mzsu5hc01#

对于链接<Link to={/posts/${post.id}}>,您需要呈现匹配的路由路径,例如path="/posts/:pid"

<Routes>
  <Route path='/posts' exact element={<Demo />} />
  <Route path='/posts/:pid' element={<DemoPost />} />
</Routes>

react-router-dom@6Route组件也不再向被路由的组件传递路由属性。element组件应该使用useParams钩子来访问路由路径参数。

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

function Post() {
  const { pid } = useParams();

  const [post, setPost] = useState();

  useEffect(() => {
    fetch(`https://jsonplaceholder.typicode.com/posts/${pid}`)
      .then(response => response.json())
      .then(json => setPost(json));
  }, [pid]); // <-- pid is effect dependency

  if (!post) {
    return null; // <-- or loading indicator/spinner/etc
  }

  return (
    <div className="posts">
      <div className="post-container">
        <h1>{post.title}</h1>
        <p>{post.body}</p>
      </div>
    </div>
  );
}

相关问题