import React,{useEffect, useState} from 'react'
//import {Link} from 'react-router-dom'
import { FcLikePlaceholder, FcComments } from "react-icons/fc";
const SinglePost = () => {
const [data,setdata] = useState([])
const callSinglePage = async () => {
try {
const res = await fetch('/post/:id', {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
credentials: "include"
});
const data = await res.json();
console.log(data);
setdata(data.post);
if(!res.status === 200){
const error = new Error(res.error);
throw error;
}
} catch(err) {
console.log(err);
}
}
useEffect(()=>{
callSinglePage();
});
return (
<div className="bg">
<h2>Confession</h2>
<h5>Read Secrets</h5>
<div>
{
data.map(post=>{
return (
<div className = "confession">
<div className="post">
<h3>{post.heading}</h3>
</div>
<div className="body-2">
<p>{post.confess}</p>
</div>
<FcLikePlaceholder size="2em"/>
<FcComments style={{position:'relative',left:'20px'}}size="2em"/>
</div>
)
})
}
</div>
</div>
)}
export default SinglePost
App.js:
<Route path = '/post/:id'>
{user ? <SinglePost/> : <Signup/>}
</Route>
router.get('/post/:id',authenticate,async (req,res)=>{
try {
const post = await Post.findById(req.params.id);
res.status(200).json(post);
} catch(err) {
res.status(500).json(err);
}
})
在邮差,我得到的单一职位,这意味着后端工作良好。为什么地图没有定义?取写,URL中写http://localhost:3000/post/612a241ec1ac483f08e78c78id是正确的,但它不起作用
错误:
TypeError: Cannot read property 'map' of undefined
src/components/SinglePost.js:42
39 | <div className="bg">
40 | <h2>Confession</h2>
41 | <h5>Read Secrets</h5>
> 42 | <div>
| ^ 43 | {
44 | data.map(post=>{
45 | return(
View compiled
▶ 18 stack frames were collapsed.
callSinglePage
src/components/SinglePost.js:22
19 |
20 | const data = await res.json();
21 | console.log(data);
> 22 | setdata(data.post);
| ^ 23 |
24 | if(! res.status === 200){
25 | const error = new Error(res.error);
请帮助。
您需要从参数中读取Id。
const { id } = useParams();
代码中的问题是fetch中的/post/:id
行。您需要将id替换为从url接收到的id。
一旦你读取了Id,你需要传递给你的取回调用作为
fetch(`/post/${id}`)
如果你的数据。post是一个对象,那么你的代码将再次失败,因为你不能在一个对象上做.map
。因此,当设置状态时,您需要执行([data.post])