| import React, { useEffect, useState } from 'react'; | |
| import { useNavigate, useLocation, useParams } from 'react-router-dom'; | |
| import { getAnnouncementDetail } from '../api/announcement'; | |
| import { message } from 'antd'; | |
| import './AnnouncementDetail.css'; | |
| const AnnouncementDetail = () => { | |
| const navigate = useNavigate(); | |
| const { id } = useParams(); | |
| const [announcement, setAnnouncement] = useState(null); | |
| const [loading, setLoading] = useState(true); | |
| const [error, setError] = useState(''); | |
| const location = useLocation(); | |
| const { state } = useLocation(); | |
| const handleBack = () => { | |
| const fromTab = location.state?.fromTab; // 从跳转时传递的 state 中获取 | |
| if (fromTab) { | |
| navigate(`/dashboard/${fromTab}`); // 明确返回对应标签页 | |
| } else { | |
| navigate(-1); // 保底策略 | |
| } | |
| } | |
| useEffect(() => { | |
| const fetchAnnouncement = async () => { | |
| try { | |
| setLoading(true); | |
| const response = await getAnnouncementDetail(id); | |
| if (response.data.code === 200) { | |
| setAnnouncement(response.data.data.announcement); | |
| } else { | |
| setError(response.data.message || '获取公告详情失败'); | |
| } | |
| } catch (err) { | |
| setError('获取公告详情失败'); | |
| message.error('获取公告详情失败'); | |
| } finally { | |
| setLoading(false); | |
| } | |
| }; | |
| fetchAnnouncement(); | |
| }, [id]); | |
| if (error || !announcement) { | |
| return ( | |
| <div className="announcement-container"> | |
| <button className="back-button" onClick={handleBack}> | |
| ← 返回 | |
| </button> | |
| <div className="error-message">{error || '公告不存在'}</div> | |
| </div> | |
| ); | |
| } | |
| return ( | |
| <div className="announcement-container"> | |
| <button className="back-button" onClick={handleBack}> | |
| ← 返回 | |
| </button> | |
| <div className="announcement-detail"> | |
| <div className="announcement-header"> | |
| <h1>{announcement.title}</h1> | |
| <div className="announcement-meta"> | |
| <span>发布日期:{announcement.createTime}</span> | |
| </div> | |
| </div> | |
| <div className="announcement-content"> | |
| {announcement.content.split('\n').map((paragraph, i) => ( | |
| <p key={i}>{paragraph}</p> | |
| ))} | |
| </div> | |
| </div> | |
| </div> | |
| ); | |
| }; | |
| export default AnnouncementDetail; | |