Krishya | 767f9b9 | 2025-06-05 23:59:37 +0800 | [diff] [blame] | 1 | // src/pages/UserInfo.js |
| 2 | import React, { useEffect, useState } from 'react'; |
| 3 | import axios from 'axios'; |
| 4 | import { useLocation } from 'wouter'; |
| 5 | |
| 6 | const DEFAULT_AVATAR_URL = '/default-avatar.png'; // 替换为你的默认头像地址 |
| 7 | |
| 8 | const UserInfo = () => { |
| 9 | const [location] = useLocation(); |
| 10 | const userId = location.split('/').pop(); |
| 11 | const [userInfo, setUserInfo] = useState(null); |
| 12 | const [error, setError] = useState(null); |
| 13 | |
| 14 | useEffect(() => { |
| 15 | const fetchUserInfo = async () => { |
| 16 | try { |
| 17 | setError(null); |
| 18 | const { data: raw } = await axios.get(`/echo/user/${userId}/getProfile`); |
| 19 | |
| 20 | if (!raw) { |
| 21 | setError('用户数据为空'); |
| 22 | setUserInfo(null); |
| 23 | return; |
| 24 | } |
| 25 | |
| 26 | const profile = { |
| 27 | avatarUrl: raw.avatarUrl |
| 28 | ? `${process.env.REACT_APP_AVATAR_BASE_URL}${raw.avatarUrl}` |
| 29 | : DEFAULT_AVATAR_URL, |
| 30 | nickname: raw.username || '未知用户', |
| 31 | email: raw.email || '未填写', |
| 32 | gender: raw.gender || '保密', |
| 33 | bio: raw.description || '无', |
| 34 | interests: raw.hobbies ? raw.hobbies.split(',') : [], |
| 35 | level: raw.level || '未知', |
| 36 | experience: raw.experience ?? 0, |
| 37 | uploadAmount: raw.uploadCount ?? 0, |
| 38 | downloadAmount: raw.downloadCount ?? 0, |
| 39 | shareRate: raw.shareRate ?? 0, |
| 40 | joinedDate: raw.registrationTime, |
| 41 | }; |
| 42 | |
| 43 | setUserInfo(profile); |
| 44 | } catch (err) { |
| 45 | setError(err.response?.status === 404 ? '用户不存在' : '请求失败,请稍后再试'); |
| 46 | setUserInfo(null); |
| 47 | } |
| 48 | }; |
| 49 | |
| 50 | fetchUserInfo(); |
| 51 | }, [userId]); |
| 52 | |
| 53 | if (error) return <p>{error}</p>; |
| 54 | if (!userInfo) return <p>加载中...</p>; |
| 55 | |
| 56 | return ( |
| 57 | <div className="user-profile"> |
| 58 | <img src={userInfo.avatarUrl} alt="头像" /> |
| 59 | <h2>{userInfo.nickname}</h2> |
| 60 | <p>邮箱:{userInfo.email}</p> |
| 61 | <p>性别:{userInfo.gender}</p> |
| 62 | <p>简介:{userInfo.bio}</p> |
| 63 | <p>兴趣爱好:{userInfo.interests.join('、')}</p> |
| 64 | <p>等级:{userInfo.level}</p> |
| 65 | <p>经验值:{userInfo.experience}</p> |
| 66 | <p>上传量:{userInfo.uploadAmount}</p> |
| 67 | <p>下载量:{userInfo.downloadAmount}</p> |
| 68 | <p>分享率:{userInfo.shareRate}</p> |
| 69 | <p>注册时间:{userInfo.joinedDate}</p> |
| 70 | </div> |
| 71 | ); |
| 72 | }; |
| 73 | |
| 74 | export default UserInfo; |