我想在添加新评论后更新组件,该评论将存储到后端,并使用具有新评论的新组件更新之前显示的组件。
这是加载单个帖子/文章及其评论的 Page.js:
import React ,{useState, useContext, useEffect}from 'react';
import {useHistory,Redirect, useParams} from 'react-router-dom'
import axios from 'axios'
import '../CSS/Page.css'
import CreateComment from './CreateComment';
const Page=()=>{
const [show,setShow]=useState({
commentBox:false
})
const [post,setPost] = useState(
{id:'', username:'', title:'',body:'',date:'',comments:[{}]
})
let {postTitle}=useParams()
useEffect(() => {
axios.get(`http://localhost:2000/apiEndpoint/singlePost/${postTitle}`,{withCredentials:true},{
headers: {
'Content-Type': 'application/json'
}
}).then((res)=>{
console.log(res.data)
const postS=res.data
setPost({...post,id:postS._id, username:postS.username, title:postS.title, body:postS.body,comments: postS.comments})
return;
}).catch((err)=>{
console.log([err])
})
},[]);
const handleCommentButton=(e)=>{
setShow({ ...show, commentBox:!show.commentBox });
}
return (
<div className='postContainer'>
<div className='singlePostcontainer'>
<div className='singlePost' >
<h1>{post.title}</h1>
<hr/>
<p>{post.body} </p>
{post.id}
<hr/>
<h5>Comments:<button className='btnCom' onClick={handleCommentButton}>{show.commentBox?'Close':'Add Comment'}</button></h5>
{show.commentBox?(<CreateComment post={post} />):''}
{post.comments.map(comment=>{
const commentID=comment._id
return(
<div className='comment' key={commentID}>
<h3>{comment.body}</h3>
<h6>By: {comment.creater}</h6>
</div>
)
})}
</div>
</div>
</div>
)
}
export default Page
这是 CreateComment.js 组件,它具有对数据库的表单和 POST 请求:
import React, { Component,useState, useEffect, lazy } from 'react';
import Cookies from 'js-cookie';
import { Link, Redirect } from 'react-router-dom';
const axios = require('axios').default;
const CreateComment=(props)=>{
var commentStr={
body:''
}
const [comment, setComment] = useState(commentStr);
const handleSubmitA=(e)=>{
e.preventDefault()
console.log('This is the id:',props.post.id)
axios.post(`http://localhost:2000/apiEndpoint/CREATE/comment/${props.post.id}`,{
body:comment.body
},
{withCredentials:true},{
headers: {
'Content-Type': 'application/json'
}}).then(res=>{
console.log(res);
})
}
const handleChangeA=(e)=>{
const {name,value}=e.target
setComment({ ...comment, [name]: value });
}
return(
<div className='commentContainer'>
<form onSubmit={handleSubmitA}>
<label>Enter Comment</label>
<textarea name="body" onChange={handleChangeA}></textarea>
<button>Submit</button>
</form>
</div>
)
}
export default CreateComment
我能够成功添加组件,并且还将评论发布到后端数据库。但只有当我按重新加载时,它才会显示在页面上。
我从 useEffect Hook 内部删除了空数组。它给了我一个无限循环,但工作正常。但是,由于这不是一个好的做法,而且它会占用本地存储资源,我怎样才能执行相同的任务而不出现无限循环?
最佳答案
您可能有一个陈旧的关闭。 https://dmitripavlutin.com/react-hooks-stale-closures/
试试这个:
setPost(prevState => ({
...prevState,
id: postS._id,
username: postS.username,
title: postS.title,
body: postS.body,
comments: postS.comments
}))
关于javascript - 在将新项目添加到数据库后,如何使用 React hooks 更新 React 中的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64430500/