You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React评论框提交POST请求后需刷新取数的解决方案咨询

React评论框提交后无需刷新显示新评论的解决方案

你的核心问题是:Blogs2组件提交评论后只更新了自身的本地状态,但主组件依赖的是Redux存储的评论数据,两者状态不同步,导致新评论必须刷新页面才会显示。下面提供两种实用的解决思路:

方案1:利用Redux同步状态(推荐)

既然已经用Redux管理评论数据,直接在提交成功后更新Redux状态是最合理的方式,无需额外请求整个评论列表。

步骤1:添加Redux Action和Reducer处理逻辑

首先在你的commentsActions.js中新增一个添加评论的action:

// actions/commentsActions.js
export const addComment = (comment) => ({
  type: 'ADD_COMMENT',
  payload: comment
});

然后在commentsReducer.js中处理这个action,把新评论加入列表:

// reducers/commentsReducer.js
const initialState = [];

export default function commentsReducer(state = initialState, action) {
  switch (action.type) {
    case 'FETCH_COMMENTS_SUCCESS': // 你现有的获取评论成功的action
      return action.payload;
    case 'ADD_COMMENT':
      return [action.payload, ...state]; // 新评论放在列表最前面,和你之前本地状态更新逻辑一致
    default:
      return state;
  }
}

步骤2:修改Blogs2组件使用Redux Dispatch

去掉Blogs2自身的comments本地状态,改用Redux管理,提交成功后dispatch添加评论的action:

import React, { useState} from 'react'
import axios from 'axios'
import { Row } from 'react-bootstrap'
import { useDispatch } from 'react-redux'
import { addComment } from '../actions/commentsActions'

const Blogs2 = () => {
    const [author, setAuthor] = useState('');
    const [text, setText] = useState('');
    const dispatch = useDispatch();

    const client = axios.create({
        baseURL: "http://localhost:5000/comments/" 
    });
  
    const addPosts = (author, text) => {
       client
          .post('', {
             author: author,
             text: text,
          })
          .then((response) => {
             // 将新评论同步到Redux
             dispatch(addComment(response.data));
          });
       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

这样,提交成功后Redux状态会更新,主组件通过useSelector感知到变化,自动重新渲染显示新评论。

方案2:父组件传递回调刷新评论

如果不想修改Redux的现有逻辑,可以通过主组件给Blogs2传递回调函数,提交成功后触发重新拉取评论。

步骤1:主组件传递回调函数

修改Blogs组件,新增刷新评论的函数并传递给Blogs2:

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)

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

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

  return (
    <Container>
      {/* 传递回调给Blogs2 */}
      <Blogs2 onCommentAdded={refreshComments} />
      {comments.map(comment=>(
        <Col key={comment._id} sm={12} md={6} lg={4} xk={3} >
            <Message comment={comment} />
        </Col>))}
    </Container>
  )  
}

export default Blogs

步骤2:Blogs2组件调用回调

修改Blogs2组件,在POST成功后调用父组件传递的回调:

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

const Blogs2 = ({ onCommentAdded }) => {
    const [author, setAuthor] = useState('');
    const [text, setText] = useState('');

    const client = axios.create({
        baseURL: "http://localhost:5000/comments/" 
    });
  
    const addPosts = (author, text) => {
       client
          .post('', {
             author: author,
             text: text,
          })
          .then(() => {
             // 触发父组件的刷新逻辑
             onCommentAdded()
          });
       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

这个方案会在提交成功后重新发起GET请求拉取全部评论,实现状态同步。

方案对比

  • 方案1更高效,无需额外请求,直接同步新评论到Redux状态
  • 方案2更简单,无需修改Redux的action和reducer,但会多一次HTTP请求

你可以根据项目实际需求选择合适的方案。

内容的提问来源于stack exchange,提问作者Pepitos333

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 09:43:13