| // src/components/NotebookPage.jsx |
| |
| import React, { useState, useEffect } from 'react' |
| import { useNavigate } from 'react-router-dom' |
| import { fetchPosts, deletePost } from '../api/posts' |
| import '../style/NotebookPage.css' |
| |
| export default function NotebookPage() { |
| const navigate = useNavigate() |
| const [posts, setPosts] = useState([]) |
| const [loading, setLoading] = useState(true) |
| const [error, setError] = useState(null) |
| |
| // TODO: 替换成真实用户 ID |
| const currentUserId = 1 |
| |
| useEffect(() => { |
| async function load() { |
| try { |
| // GET /posts?user_id=1 |
| const list = await fetchPosts(currentUserId) |
| setPosts(list) |
| } catch (e) { |
| setError(e.message) |
| } finally { |
| setLoading(false) |
| } |
| } |
| load() |
| }, []) |
| |
| async function handleDelete(id) { |
| if (!window.confirm('确定要删除该帖子吗?')) return |
| try { |
| await deletePost(id) |
| setPosts(posts.filter(p => p.id !== id)) |
| alert('删除成功') |
| } catch (e) { |
| alert('删除失败:' + e.message) |
| } |
| } |
| |
| function handleEdit(id) { |
| // 假设你在路由里挂载了 /posts/edit/:postId |
| navigate(`/posts/edit/${id}`) |
| } |
| |
| if (loading) return <p>加载中…</p> |
| if (error) return <p className="error">加载失败:{error}</p> |
| |
| return ( |
| <div className="notebook-page"> |
| <h2>我的帖子管理</h2> |
| {posts.length === 0 ? ( |
| <p>暂无帖子</p> |
| ) : ( |
| <table className="post-table"> |
| <thead> |
| <tr> |
| <th>ID</th> |
| <th>标题</th> |
| <th>状态</th> |
| <th>创建时间</th> |
| <th>操作</th> |
| </tr> |
| </thead> |
| <tbody> |
| {posts.map(p => ( |
| <tr key={p.id}> |
| <td>{p.id}</td> |
| <td>{p.title}</td> |
| <td>{p.status}</td> |
| <td>{new Date(p.created_at).toLocaleString()}</td> |
| <td> |
| <button onClick={() => handleEdit(p.id)}>编辑</button> |
| <button onClick={() => handleDelete(p.id)}>删除</button> |
| </td> |
| </tr> |
| ))} |
| </tbody> |
| </table> |
| )} |
| </div> |
| ) |
| } |