我希望在提交帖子请求后刷新我的页面

问题描述 投票:0回答:1

我正在使用 React 前端创建一个评论框;主要组件有另一个嵌套组件和一个子组件。

这是主要成分:

import { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { fetchComments } from '../actions/commentsActions'
import { selectComments } from '../selectors/commentsSelectors'
import Message from '../components/Message'
import { Col, Container } from 'react-bootstrap'
import Blogs2 from './Blogs2'


const Blogs = () => {

  const dispatch = useDispatch()
  const comments = useSelector(selectComments)

  useEffect(() => {
    dispatch(fetchComments())
  }, [dispatch])


return (
    <Container>

      <Blogs2 />
  {comments.map(comment=>(
    <Col key={comment._id} sm={12} md={6} lg={4} xk={3} >
        <Message comment={comment} />
    </Col>))}
    </Container>
    )  

  }
export default Blogs

这是我编写帖子请求的嵌套组件:

import React, { useState} from 'react'
import axios from 'axios'
import { Row } from 'react-bootstrap'

const Blogs2 = () => {


    const [author, setAuthor] = useState('');
    const [text, setText] = useState('');
    const [comments, setComments] = useState([]);
 

    const client = axios.create({
        baseURL: "http://localhost:5000/comments/" 
      });
  
 
    const addPosts = (author, text) => {
       client
          .post('', {
             author: author,
             text: text,
          })
          .then((response) => {
             setComments([response.data, ...comments]);
          });
       setAuthor('');
       setText('');
    };

  const handleSubmit = (e) => {
       e.preventDefault();
       addPosts(author, text);
      };

  return ( 
   
   
     <Row>
       <form onSubmit={handleSubmit}>
       <input value={author} onChange={(e)=>setAuthor(e.target.value)} />
       <input value={text} onChange={(e)=>setText(e.target.value)} /> 
       <input type='submit' />
       </form>
   </Row>
  
  )
}

export default Blogs2

这是子组件:

import React from 'react'
import { Row } from 'react-bootstrap'
import './css/Message.css'


const Message = ({comment}) => {
  return (
    <Row id='commenti'>
      <h1>{comment.author}</h1>
      <h1>{comment.text}</h1>
   </Row>
    
  )
}

export default Message

一切正常,直到提交表单并完成发布请求时,我需要重新加载我的页面,以便之后完成我的获取请求。你有什么建议吗?

reactjs forms post get page-refresh
1个回答
0
投票

如果您希望完全重新加载页面,您可以使用

window.location.reload();

或 您可以创建一个函数refreshData Blogs组件来获取评论并将其作为道具传递给Blogs2组件,从Blogs2调用refreshData。

 const refreshData = () => {
     dispatch(fetchComments())
    }

<Blogs2 refreshData = {refreshData}/>

const addPosts = (author, text) => {
       client
          .post('', {
             author: author,
             text: text,
          })
          .then((response) => {
             setComments([response.data, ...comments]);
             props.refreshData();
          });
       setAuthor('');
       setText('');
    };
© www.soinside.com 2019 - 2024. All rights reserved.