blob: 42142133b893306f0bdade5743aef53f3d9d6c55 [file] [log] [blame]
// src/components/NotebookPage.jsx
import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { fetchPosts, deletePost } from '../api/posts_wzy'
import { getUserInfo } from '../utils/auth' // ← 导入 getUserInfo
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)
// 从 auth 获取当前用户信息
const userInfo = getUserInfo()
const currentUserId = userInfo?.id
useEffect(() => {
if (!currentUserId) {
setError('未获取到用户信息,无法加载帖子。')
setLoading(false)
return
}
async function load() {
try {
// GET /posts?user_id=currentUserId
const list = await fetchPosts(currentUserId)
setPosts(list)
} catch (e) {
setError(e.message)
} finally {
setLoading(false)
}
}
load()
}, [currentUserId])
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) {
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>
)
}