blob: 80abc3fb75033b22f741eefb16d5ffffff67f116 [file] [log] [blame]
wu90da17b2025-06-19 12:45:29 +08001// src/components/NotebookPage.jsx
2
3import React, { useState, useEffect } from 'react'
4import { useNavigate } from 'react-router-dom'
5import { fetchPosts, deletePost } from '../api/posts'
6import '../style/NotebookPage.css'
7
8export default function NotebookPage() {
9 const navigate = useNavigate()
10 const [posts, setPosts] = useState([])
11 const [loading, setLoading] = useState(true)
12 const [error, setError] = useState(null)
13
14 // TODO: 替换成真实用户 ID
15 const currentUserId = 1
16
17 useEffect(() => {
18 async function load() {
19 try {
20 // GET /posts?user_id=1
21 const list = await fetchPosts(currentUserId)
22 setPosts(list)
23 } catch (e) {
24 setError(e.message)
25 } finally {
26 setLoading(false)
27 }
28 }
29 load()
30 }, [])
31
32 async function handleDelete(id) {
33 if (!window.confirm('确定要删除该帖子吗?')) return
34 try {
35 await deletePost(id)
36 setPosts(posts.filter(p => p.id !== id))
37 alert('删除成功')
38 } catch (e) {
39 alert('删除失败:' + e.message)
40 }
41 }
42
43 function handleEdit(id) {
44 // 假设你在路由里挂载了 /posts/edit/:postId
45 navigate(`/posts/edit/${id}`)
46 }
47
48 if (loading) return <p>加载中…</p>
49 if (error) return <p className="error">加载失败:{error}</p>
50
51 return (
52 <div className="notebook-page">
53 <h2>我的帖子管理</h2>
54 {posts.length === 0 ? (
55 <p>暂无帖子</p>
56 ) : (
57 <table className="post-table">
58 <thead>
59 <tr>
60 <th>ID</th>
61 <th>标题</th>
62 <th>状态</th>
63 <th>创建时间</th>
64 <th>操作</th>
65 </tr>
66 </thead>
67 <tbody>
68 {posts.map(p => (
69 <tr key={p.id}>
70 <td>{p.id}</td>
71 <td>{p.title}</td>
72 <td>{p.status}</td>
73 <td>{new Date(p.created_at).toLocaleString()}</td>
74 <td>
75 <button onClick={() => handleEdit(p.id)}>编辑</button>
76 <button onClick={() => handleDelete(p.id)}>删除</button>
77 </td>
78 </tr>
79 ))}
80 </tbody>
81 </table>
82 )}
83 </div>
84 )
85}