reactjs - 提交表单后刷新评论列表
问题描述
我正在创建一个评论框。
我正在尝试在提交表单后刷新评论列表。
#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 方法。或者我必须改变一些其他的东西才能让它工作。
解决方案
解决这个问题的一种方法是将状态移动到您的父组件,即对父组件 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>
);
}
推荐阅读
- php - 使用适用于 SQL Server 的 ODBC 驱动程序的语法错误
- sql - SQL - 引用内容中特定位置的表?
- javascript - 可以在没有 google recaptcha v2 验证的情况下提交联系表
- r - 当数据元素出现在列组中时,将按多列分组并汇总的 R 代码
- r - 如何根据R中另一个表中的日期返回查询中的列
- python-3.x - 用户输入代码返回错误响应
- python - 更新现有行以插入 json 数组 - postgresql
- angular - 当不需要返回时我如何执行可观察的
- angular - 来自 Git 存储库的子目录的“npm install”
- php - PHP | 多次调用 API 作为不同的链接并获取数据