如何解决Reactjs:点击标题显示博客文章内容
我正在尝试使用 MERN 堆栈制作博客站点。所以这里我有我的博客组件,它从数据库中获取所有博客文章并显示如下
这是上面图片的反应代码
import { useEffect,useState } from "react";
import axios from 'axios';
import BlogDetails from "./BlogDetails";
const Blogs = () => {
const [blogPost,setPosts] = useState([])
useEffect(()=>{
const fetchBlog = async ()=>{
const blogsData = await axios('http://localhost:4000/blogs')
const blogsFetched = blogsData.data
console.log(blogsFetched);
setPosts(blogsFetched)
}
fetchBlog()
},[])
return (
<div className="blogs content">
<h2>All Blogs</h2>
{ blogPost.map((post)=>(
<div key={post._id}>
<a className="single" href={post._id}>
<h3 className="title" >{post.title}</h3>
<p className="snippet">{post.snippet}</p>
</a>
</div>
))
}
</div>
);
}
export default Blogs;
我想在我点击上面页面的标题时详细显示特定的博客文章。
单击标题时,这些详细信息将作为道具传递给另一个名为 BlogDetails 的组件并进行呈现。我被卡住的部分是使用 blogpost id 路由到 BlogDetails 组件。有什么办法可以在点击标题时使用Route来渲染BlogDetails组件?
请帮忙
解决方法
假设您使用的是 react-router,您可以执行以下操作:
const history = useHistory();
.
.
.
<div onClick={() => history.push(`/blog/${post.id}`)}>
<h3 className="title">{post.title}</h3>
</div>
然后您的路由器将呈现您指定要为 /blog
路由呈现的组件。在该路由中,您可以使用 useLocation 获取 url,然后通过拆分 url 来解析 id。
const { pathName } = useLocation(); // also from react-router
或者(更优雅),您可以在执行 history.push 时推送状态片段,例如:
...onClick={() => history.push(`/blog${post.id}`,{ blogId: ${post.id}})}
然后在随后呈现的组件中再次使用 useLocation
来传递状态:
const { state } = useLocation();
,
是的,您可以为 BlogDetail 组件使用路由
在 BrowserRouter 中添加 BlogDetail 链接
<Route path={'url'} render={(props) => <BlogDetail/>}/>
在博客组件中使用 react router dom 的链接,然后像这样在渲染 html 的标题上使用此链接
import { Link } from "react-router-dom";
{ blogPost.map((post)=>(
<div key={post._id}>
<a className="single" href={post._id}>
<Link to={{
pathname:'url',// this will be your url of BlogDetail
state: post //if you want post object detail in next component
}}>
<h3 className="title" >{post.title}</h3>
</Link>
<p className="snippet">{post.snippet}</p>
</a>
</div>
))
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。