首页 > 解决方案 > 提交表单后刷新评论列表

问题描述

我正在创建一个评论框。

我正在尝试在提交表单后刷新评论列表。

#CommentBox.js
const CommentBox = (props) => {
return (
    <div className="comment_area clearfix mb-5">
        <div className="section-heading style-2 mb-5">
            <h4>Comment</h4>
            <div className="line"></div>
        </div>
        < CommentForm />
        < CommentList />
    </div>
    
 );
}

如您所见,我为 CommentForm.js 和 CommentList.js 提供了不同的组件

#CommentForm.js
 const onSubmitHandler = (e) => {
 ........
  axios.post(......................)
 ................................
  }
  return (
         <form onSubmit={onSubmitHandler}>
         |
         |
         </form>
 );

#CommentList.js
 useEffect(() => {
    const id = props.postId;
    const fetchData = async () => {
      try {
        
        const res = await axios.get(
          `.......................`
        )
        setComments(res.data.results);
      } catch (err) {}
    };
    fetchData();
}, [props.postId])

return (
.................
.................
......
)

我应该如何以 onsubmitHandler() 形式编写 GET 方法。或者我必须改变一些其他的东西才能让它工作。

标签: reactjsreact-redux

解决方案


解决这个问题的一种方法是将状态移动到您的父组件,即对父组件 CommentBox 进行 axio 调用。CommentForm 通过回调通知父表单已提交,然后您将一个 axios 调用一个接一个地链接,将 GET 结果传递给 CommentList。

const CommentBox = (props) => {

const [comments, setComments] = useState([]);

const onSubmitHandler = (e) => {
 ........
  axios.post(.......)
       .then(() => axios.get())
       .then((res) => setComments(res.data);
}

return (
    <div className="comment_area clearfix mb-5">
        <div className="section-heading style-2 mb-5">
            <h4>Comment</h4>
            <div className="line"></div>
        </div>
        < CommentForm onSubmit={onSubmitHandler}/>
        < CommentList comments={comments}/>
    </div>
 );
}

推荐阅读