Node.js 在React中显示添加的帖子而不刷新页面

Node.js 在React中显示添加的帖子而不刷新页面,node.js,reactjs,mongodb,Node.js,Reactjs,Mongodb,我一直在大学外从事一个个人项目,开发一个博客。 现在,我正在尝试实现一个“主页”,在成功登录后,用户可以发布文本,然后它会出现在你可以在图片中看到的createpost div下 这就是我迄今为止所取得的成就: 现在我可以登录,发布一篇新的帖子,并将其保存在数据库中 这是用户登录后看到的home.js功能组件: import '../App.css'; import { useHistory } from "react-router-dom"; import React , {useS

我一直在大学外从事一个个人项目,开发一个博客。 现在,我正在尝试实现一个“主页”,在成功登录后,用户可以发布文本,然后它会出现在你可以在图片中看到的createpost div下 这就是我迄今为止所取得的成就:

现在我可以登录,发布一篇新的帖子,并将其保存在数据库中

这是用户登录后看到的home.js功能组件:

import '../App.css';    
import { useHistory } from "react-router-dom";
import React , {useState, useEffect} from 'react';
import jwt_decode from 'jwt-decode'
import logo from '../images/home-logo.png';
import {Col,Form,Input,Button,Card,CardTitle,Navbar,Nav,NavbarBrand} from 'reactstrap'
import { createPost,getUserPosts } from '../fucntions/user_functions'
function Home(){
    var _decoded;
    var _email;
    let history = useHistory();
    const[post_text,setPost] = useState('');

    const handleChangePost = e =>{ setPost(e.target.value);};


    function handlePost(e){
      e.preventDefault();
      const toPost = {
        post :post_text, email :_email
      }
      createPost(toPost).then(res =>{
        setPost('')
      })
    }

    function getPosts() {
      const container ={
        email:_email
      }
      getUserPosts(container).then(res=>{

      })
    }



    function handleLogout (e) {
        e.preventDefault();
        localStorage.removeItem('usertoken')  
        history.push(`/login`)
    }
    useEffect(() =>{
        if (localStorage.getItem("usertoken") === null) {
            history.push('/login')
        } else {
        const token = localStorage.usertoken
        const user_email = localStorage.useremail
        const decoded = jwt_decode(token)
        _decoded = decoded;
        _email = decoded.email
        getPosts()

    };
});
    return (
      <div className = "box">
        <div>
        <Navbar color="light" light expand="md">
                    <Nav>
                        <NavbarBrand type = "button" onClick = {handleLogout}>Logout</NavbarBrand>
                    </Nav>
        </Navbar>
        <div className = "wrapper">
           <Card body outline color="secondary" className = "card-home " >
            <CardTitle><img src={logo} alt="logo"></img>Create post</CardTitle>
            <Form onSubmit = {handlePost}>
            <Input  id = "tx" name = "input1" type = "textarea" value = {post_text} placeholder="Enter your post here"  onChange= {handleChangePost}></Input>
             <br></br>
            <Col sm={{ span: 10, offset: 5 }}>
              <Button outline color="primary" type="submit">Post!</Button>
            </Col>
            </Form>
           </Card>
          </div>
      </div>

    </div>

    )

}

export default Home;
如上所述,在函数getPosts()中,响应是用户发布的所有post ID的数组,它们存储在名为“posts”的mongodb集合中 调用该函数后,我可以对它们进行迭代:

function getPosts() {
  const container ={
    email:_email
  }
  getUserPosts(container).then(res=>{
    forEach(res.posts) {

    }
  })
}
我想呈现所有这些帖子,所以每次用户发布一篇新帖子时,它都会在图片中的createpost div之后显示,最好的方法是什么?
谢谢

首先定义您的帖子收集状态:

const [allPosts, setAllPosts] = useState([]);
然后,每次在数据库中成功保存帖子时,将其附加到该状态:

function handlePost(e){
  e.preventDefault();
  const toPost = {
    post :post_text, email :_email
  }
  createPost(toPost).then(res =>{
    setPost('')
    setAllPosts(allPosts.concat(toPost);
  })
}
getPosts也是如此:

   function getPosts() {
      const container ={
        email:_email
      }
      getUserPosts(container).then(res=>{
          setAllPosts(res.data); // <-- if the data is the same structure as the created before
      })
    }
函数getPosts(){ 常量容器={ 电子邮件:\ u电子邮件 } getUserPosts(容器)。然后(res=>{ setAllPosts(res.data);//{ 返回电子邮件:{post.email}post:post.post }) } )
请随意更改HTML结构,使其与您的设计相匹配

首先定义您的帖子集合状态:

const [allPosts, setAllPosts] = useState([]);
然后,每次在数据库中成功保存帖子时,将其附加到该状态:

function handlePost(e){
  e.preventDefault();
  const toPost = {
    post :post_text, email :_email
  }
  createPost(toPost).then(res =>{
    setPost('')
    setAllPosts(allPosts.concat(toPost);
  })
}
getPosts也是如此:

   function getPosts() {
      const container ={
        email:_email
      }
      getUserPosts(container).then(res=>{
          setAllPosts(res.data); // <-- if the data is the same structure as the created before
      })
    }
函数getPosts(){ 常量容器={ 电子邮件:\ u电子邮件 } getUserPosts(容器)。然后(res=>{ setAllPosts(res.data);//{ 返回电子邮件:{post.email}post:post.post }) } )
请随意更改HTML结构,使其与您的设计相匹配

谢谢!它可以工作,但发布过程非常缓慢(发布后,文本显示非常缓慢),您知道原因吗?是的,这是因为您首先将其保存在数据库中,然后在收到回复200(成功)时,然后清除文本。您可以将文本保存在一个变量中,清除文本,然后将其发布到服务器,但我不建议这样做,因为如果服务器出现故障,您的字段将被清除,这将导致错误的用户体验。谢谢!它可以工作,但发布过程非常缓慢(发布后,文本显示速度非常慢),您知道为什么吗?是的,这是因为您首先将其保存在数据库中,当收到响应200(成功)时,然后清除文本。您可以将文本保存在变量中,清除文本,然后将其发布到服务器,但我不建议这样做,因为如果服务器出现故障,您的字段将被清除,这将导致错误的用户体验。