我想使一个博客网站的单一博客页面阅读,但它不工作
我需要有人帮我解决这个错误。
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
1条答案
按热度按时间mzsu5hc01#
对于链接
<Link to={
/posts/${post.id}}>
,您需要呈现匹配的路由路径,例如path="/posts/:pid"
。react-router-dom@6
Route
组件也不再向被路由的组件传递路由属性。element
组件应该使用useParams
钩子来访问路由路径参数。