我正在使用React Hooks创建一个简单的博客。对于路由器,我正在使用useParams()。所有博客文章都在首页上,如果您单击标题,它将带您到单个文章页面。
我可以通过在Page组件上编写const {id} = useParams(); console.log(id);
来显示单击的文章的ID。但是,如何在单个文章页面上显示标题和文本?我尝试了.find方法,但似乎不起作用。
The data of blog posts
[
{
"id": "1oQAPxRl2k7Spev10qFE",
"text": "Looooorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostr.",
"title": "Title#1"
},
{
"id": "ThRwQIgpLUB7iBq1H8VI",
"text": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident.",
"title": "Title#2"
},
{
"id": "aJvajhmoCXbfU7RJVkzn",
"text": "Nuncccc sit amet ante convallis, semper metus ut, ornare leo. Fusce tellus metus, commodo at massa non, auctor pharetra ipsum. Maecenas in suscipit nulla. Nam in consectetur dui, non laoreet purus. Aliquam erat volutpat. Etiam non risus vestibulum, ornare mauris ut, pretium mauris. Nam ac rutrum odio. Vestibulum feugiat scelerisque elementum. Sed condimentum risus nec sem sodales porta. Proin mollis suscipit neque, facilisis luctus nisi feugiat nec. Duis efficitur orci vel ullamcorper rhoncus. Fusce ante ipsum, facilisis non purus nec, aliquam fringilla nibh. ",
"title": "Title#3"
},
{
"id": "pFFNhyrv3aJJg8Cq18Fx",
"text": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"title": "Title#4"
}
]
import React, { useState, useEffect } from 'react';
import Header from './Header';
import Page from '../pages/Page'
import { db } from "../Firebase";
import {
BrowserRouter as Router,
Route,
Switch
} from 'react-router-dom';
const App = () => {
const [articles, setArticles] = useState([]);
useEffect(() => {
const unsubscribe = db
.collection('articles')
.onSnapshot((snapshot) => {
const newArticles = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data()
}))
setArticles(newArticles)
})
return () => unsubscribe()
}, []);
return (
<div>
<Router>
<Header />
<Switch>
<Route exact path="/" render={() => <Home articles={articles} />} />
<Route exact path="/page/:id/" render={() => <Page articles={articles} />} />
</Switch>
</Router>
</div>
);
}
export default App;
import React from 'react';
import { Link } from 'react-router-dom'
function Header(props) {
return (
<div>
<h1>Title</h1>
<ul>
<li><Link to='/' >Home</Link></li>
</ul>
</div>
);
}
export default Header;
import React from 'react';
import { useParams } from 'react-router';
function Page(props) {
return (
<div>
*** Title of clicked article ***
*** Text of clicked article ***
</div>
);
}
export default Page;