[英]Viewing a single post with mongodb in react.js
我正在開始一個小博客。 我想單擊帖子標題並查看單個帖子。 App.js頁面:
**import React from 'react'
import Nav from './Nav'
import {useState, useEffect} from 'react'
import {Link} from 'react-router-dom'
const App = () => {
const [posts, setPosts] = useState ([])
useEffect (() => {
const fetchData = async () => {
const res = await fetch (`http: // localhost: 3030 / api / posts`)
const data = await res.json ()
setPosts (date)
}
fetchData ()
}, [])
return (
<div className = 'container p-5'>
<Nav />
<h1 style = {{marginTop: '20px'}}> MERN CRUD </h1>
{
posts.map ((post, id) => {
return (
<div key = {id} className = 'row' style = {{borderBottom: '3px solid black', paddingTop: '30px', paddingBottom: '30px'}}>
<Link to = {`/ post / $ {post.slug}`}>
<h1> {post.title} </h1>
</Link>
<h5> Created at: {new Date (post.createdAt) .toLocaleDateString ()} </h5>
<h6> Written by: {post.user} </h6>
<p> {post.content.substring (0, 100)} ...... </p>
</div>
)
})
}
</div>
)
}
export default App**
我想通過 slug 發出請求。 SinglePost.js 頁面
**import React from 'react'
import {useState, useEffect} from 'react'
import Nav from './Nav'
const SinglePost = (props) => {
const [post, setPost] = useState ('')
useEffect (() => {
const fetchPost = async () => {
const res = await fetch (`http: // localhost: 3030 / api / post / $ {props.slug}`)
const data = await res.json ()
setPost (date)
console.log (date)
}
fetchPost ()
}, [])
return (
<div>
<Nav />
<div> </div>
<h1> {post.slug} </h1>
</div>
)
}
export default SinglePost**
這是帶有查詢的頁面:
**exports.read = (req, res) => {
const { slug } = req.params
Post.findOne({slug})
.exec((err, post) => {
if(err){
console.log(err)
}else {
res.json(post)
}
})
}**
我只看到第一篇文章,我不知道如何查看具體的文章。 謝謝您的幫助
您應該定義一個Routes
組件,負責處理index.js
文件中單個帖子的重定向
import { BrowserRouter, Routes, Route } from 'react-router-dom';
const rootElement = document.getElementById('root');
render(
<BrowserRouter>
<Routes>
<Route path='/' element={<App />} />
<Route path='/post' element={<SinglePost />} />
</Routes>
</BrowserRouter>,
rootElement
);
此外,您應該使用useParams
掛鈎來檢索SinglePost
組件中的slug
參數:
import { useParams } from 'react-router-dom';
const SinglePost = () => {
const { slug } = useParams();
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.