blob: 42142133b893306f0bdade5743aef53f3d9d6c55 [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_wzy'
wu2f28f672025-06-19 14:29:30 +08006import { getUserInfo } from '../utils/auth' // ← 导入 getUserInfo
wu90da17b2025-06-19 12:45:29 +08007import '../style/NotebookPage.css'
8
9export default function NotebookPage() {
10 const navigate = useNavigate()
11 const [posts, setPosts] = useState([])
12 const [loading, setLoading] = useState(true)
13 const [error, setError] = useState(null)
14
wu2f28f672025-06-19 14:29:30 +080015 // 从 auth 获取当前用户信息
16 const userInfo = getUserInfo()
17 const currentUserId = userInfo?.id
wu90da17b2025-06-19 12:45:29 +080018
19 useEffect(() => {
wu2f28f672025-06-19 14:29:30 +080020 if (!currentUserId) {
21 setError('未获取到用户信息,无法加载帖子。')
22 setLoading(false)
23 return
24 }
25
wu90da17b2025-06-19 12:45:29 +080026 async function load() {
27 try {
wu2f28f672025-06-19 14:29:30 +080028 // GET /posts?user_id=currentUserId
wu90da17b2025-06-19 12:45:29 +080029 const list = await fetchPosts(currentUserId)
30 setPosts(list)
31 } catch (e) {
32 setError(e.message)
33 } finally {
34 setLoading(false)
35 }
36 }
37 load()
wu2f28f672025-06-19 14:29:30 +080038 }, [currentUserId])
wu90da17b2025-06-19 12:45:29 +080039
40 async function handleDelete(id) {
41 if (!window.confirm('确定要删除该帖子吗?')) return
42 try {
43 await deletePost(id)
44 setPosts(posts.filter(p => p.id !== id))
45 alert('删除成功')
46 } catch (e) {
47 alert('删除失败:' + e.message)
48 }
49 }
50
51 function handleEdit(id) {
wu90da17b2025-06-19 12:45:29 +080052 navigate(`/posts/edit/${id}`)
53 }
54
55 if (loading) return <p>加载中…</p>
56 if (error) return <p className="error">加载失败:{error}</p>
57
58 return (
59 <div className="notebook-page">
60 <h2>我的帖子管理</h2>
61 {posts.length === 0 ? (
62 <p>暂无帖子</p>
63 ) : (
64 <table className="post-table">
65 <thead>
66 <tr>
67 <th>ID</th>
68 <th>标题</th>
69 <th>状态</th>
70 <th>创建时间</th>
71 <th>操作</th>
72 </tr>
73 </thead>
74 <tbody>
75 {posts.map(p => (
76 <tr key={p.id}>
77 <td>{p.id}</td>
78 <td>{p.title}</td>
79 <td>{p.status}</td>
80 <td>{new Date(p.created_at).toLocaleString()}</td>
81 <td>
82 <button onClick={() => handleEdit(p.id)}>编辑</button>
83 <button onClick={() => handleDelete(p.id)}>删除</button>
84 </td>
85 </tr>
86 ))}
87 </tbody>
88 </table>
89 )}
90 </div>
91 )
92}