Commit d10ce005 authored by IronHammer Std's avatar IronHammer Std
Browse files

能动就是个奇迹了

parent d6b74ba9
...@@ -2,6 +2,8 @@ import { useState, useEffect } from 'react' ...@@ -2,6 +2,8 @@ import { useState, useEffect } from 'react'
import './App.css' import './App.css'
const BackEndUrl : string = 'http://localhost:8080' const BackEndUrl : string = 'http://localhost:8080'
const UsePages : boolean = true // 是否使用分页
const PageSize : number = 10 // 每页显示的评论数量
interface CommentData { interface CommentData {
name: string name: string
...@@ -19,6 +21,9 @@ function App() { ...@@ -19,6 +21,9 @@ function App() {
const [error, setError] = useState<string>('') const [error, setError] = useState<string>('')
const [loading, setLoading] = useState<boolean>(false) const [loading, setLoading] = useState<boolean>(false)
const [comments, setComments] = useState<CommentFromBack[]>([]) const [comments, setComments] = useState<CommentFromBack[]>([])
const [page, setPage] = useState<number>(1)
const [totalPage, setTotalPage] = useState<number>(1)
const [commentCount, setCommentCount] = useState<number>(0)
const clearForm = () => { const clearForm = () => {
setUsername('') setUsername('')
...@@ -50,16 +55,24 @@ function App() { ...@@ -50,16 +55,24 @@ function App() {
body: JSON.stringify(Comment), body: JSON.stringify(Comment),
}) })
const text = await response.text();
//输出responce 的详细信息到控制台 //输出responce 的详细信息到控制台
console.log('Response Status:', response.status); console.log('Response Status:', response.status);
console.log('Response Headers:', response.headers); console.log('Response Headers:', response.headers);
console.log('Response URL:', response.url); console.log('Response URL:', response.url);
console.log('Response Body:', await response.text()); console.log('Response Body:', text);
if (!response.ok) { if (!response.ok) {
throw new Error('无法提交评论,错误码:' + response.status) throw new Error('无法提交评论,错误码:' + response.status)
} }
const dataJson = JSON.parse(text)
if (dataJson.code !== 0) {
throw new Error('获取评论失败:' + dataJson.msg)
}
clearForm() clearForm()
//alert('提交成功!'); //alert('提交成功!');
fetchComments() fetchComments()
...@@ -73,12 +86,21 @@ function App() { ...@@ -73,12 +86,21 @@ function App() {
} }
} }
const fetchComments = async () => { const fetchCommentsPage = async (page : number) => {
setLoading(true) setLoading(true)
setError('') setError('')
try { try {
const response : Response = await fetch('http://localhost:8080/comment/get?size=-1', {
const params = new URLSearchParams();
if (UsePages) {
params.append('page', page.toString());
params.append('size', PageSize.toString());
} else {
params.append('size', '-1'); // -1表示获取所有评论
}
const response : Response = await fetch(BackEndUrl + '/comment/get?' + params.toString(), {
method: 'GET', method: 'GET',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
...@@ -98,10 +120,6 @@ function App() { ...@@ -98,10 +120,6 @@ function App() {
} }
const dataJson = JSON.parse(text) const dataJson = JSON.parse(text)
/*
dataJson:
{"code":0,"msg":"success","data":{"total":4,"comments":[{"id":1,"name":"Alice","content":"First comment!"},{"id":2,"name":"Bob","content":"Great work!"},{"id":3,"name":"114","content":"514"},{"id":4,"name":"114","content":"514"}]}}
*/
if (dataJson.code !== 0) { if (dataJson.code !== 0) {
throw new Error('获取评论失败:' + dataJson.msg) throw new Error('获取评论失败:' + dataJson.msg)
...@@ -111,10 +129,20 @@ function App() { ...@@ -111,10 +129,20 @@ function App() {
setComments(data) setComments(data)
console.log('获取到的评论:', data) console.log('获取到的评论:', data)
const totalImpl : number= dataJson.data?.total || 1;
const pageCount : number = Math.max(Math.ceil(totalImpl / PageSize), 1)
setTotalPage( pageCount )
setCommentCount( totalImpl )
if(page > pageCount)
{
setPage ( pageCount )
fetchCommentsPage ( pageCount )
}
} catch (err) { } catch (err) {
// 处理错误 // 处理错误
console.error('提交失败:', err) console.error('获取失败:', err)
setError('提交失败:' + (err instanceof Error ? err.message : '未知错误')) setError('获取失败:' + (err instanceof Error ? err.message : '未知错误'))
alert(error); alert(error);
} finally { } finally {
setLoading(false) setLoading(false)
...@@ -123,6 +151,60 @@ function App() { ...@@ -123,6 +151,60 @@ function App() {
return return
} }
const fetchComments = async () => fetchCommentsPage(page)
const deleteComment = async (id: number) => {
// 确认删除
if (!window.confirm('确定要删除这条评论吗?')) {
return
}
setError('')
try {
const response : Response = await fetch(BackEndUrl + '/comment/delete?id=' + id, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
})
//输出responce 的详细信息到控制台
console.log('Response Status:', response.status);
console.log('Response Headers:', response.headers);
console.log('Response URL:', response.url);
console.log('Response Body:', await response.text());
// 检查响应状态
if (!response.ok) {
throw new Error('无法删除评论,错误码:' + response.status)
}
} catch (err) {
// 处理错误
console.error('删除失败:', err)
setError('删除失败:' + (err instanceof Error ? err.message : '未知错误'))
alert(error);
} finally {
// 删除成功后重新获取评论列表
fetchComments()
}
}
const prevPage = () => {
if (page > 1) {
fetchCommentsPage(page - 1)
setPage(page - 1)
}
}
const nextPage = () => {
if (page < totalPage){
fetchCommentsPage(page + 1)
setPage(page + 1)
}
}
useEffect(() => { useEffect(() => {
// 初始加载评论 // 初始加载评论
fetchComments() fetchComments()
...@@ -173,6 +255,7 @@ function App() { ...@@ -173,6 +255,7 @@ function App() {
</div> </div>
<div className="comments-container"> <div className="comments-container">
<h3>评论列表</h3> <h3>评论列表</h3>
<p>{commentCount}条评论</p>
{!loading && error && <p className="error">{error}</p>} {!loading && error && <p className="error">{error}</p>}
{!loading && comments.length === 0 && <p>暂无评论</p>} {!loading && comments.length === 0 && <p>暂无评论</p>}
<ul> <ul>
...@@ -180,11 +263,22 @@ function App() { ...@@ -180,11 +263,22 @@ function App() {
<li key={comment.id}> <li key={comment.id}>
<p> <p>
<strong>{comment.name}</strong> <strong>{comment.name}</strong>
<button type="button" onClick={() => deleteComment(comment.id)}>
删除
</button>
</p> </p>
<p>{comment.content}</p> <p>{comment.content}</p>
</li> </li>
))} ))}
</ul> </ul>
{
UsePages && comments.length !== 0 &&
<div className="page-controls">
<button onClick={prevPage} disabled={page <= 1}>上一页</button>
<span>{page}/{totalPage}</span>
<button onClick={nextPage} disabled={page >= totalPage}>下一页</button>
</div>
}
</div> </div>
</> </>
) )
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment