今天是鐵人賽 Day18,目標是讓會員與管理員登入後都能進入「個人頁面 (Profile)」,並在此頁面中顯示自己的基本資料。
1️⃣ 修改 App.jsx 路由設定
原本 /profile 僅限 role = user 才能進入,導致管理員登入後無法看到 Profile。
今天我們將 /profile 改成 所有登入用戶 (user + admin) 都能進入。
<Route
path="/profile"
element={
<PrivateRoute>
<Profile />
</PrivateRoute>
}
/>
這樣不管是一般會員或管理員,登入後都會先跳轉到個人頁面。
2️⃣ 登入頁面 (Login.jsx)
登入後統一導向 /profile,避免不同角色在登入後需要額外判斷。
const handleSubmit = async (e) => {
e.preventDefault();
const res = await axios.post("http://localhost:3000/api/auth/login", formData);
setToken(res.data.token);
setUser(res.data.user);
// ✅ 登入後統一跳轉到 Profile
navigate("/profile");
};
3️⃣ 個人頁面 (Profile.jsx)
Profile 頁面會讀取 localStorage 中的使用者資訊,顯示基本資料。
如果角色是 admin,則額外顯示一個「進入後台」按鈕,讓管理員能快速進入 /admin。
import React from "react";
import { getUser } from "../utils/auth";
import { useNavigate } from "react-router-dom";
export default function Profile() {
const user = getUser();
const navigate = useNavigate();
return (
<div className="bg-white shadow-md rounded-lg p-6 max-w-md mx-auto">
<h2 className="text-2xl font-bold mb-4">個人資料</h2>
<p><strong>帳號:</strong>{user?.username}</p>
<p><strong>Email:</strong>{user?.email}</p>
<p><strong>角色:</strong>{user?.role}</p>
{user?.role === "admin" && (
<button
onClick={() => navigate("/admin")}
className="mt-4 bg-orange-500 text-white px-4 py-2 rounded"
>
進入後台
</button>
)}
</div>
);
}
4️⃣ 測試流程
一般會員登入 → /profile 顯示帳號、信箱、角色資訊
管理員登入 → /profile 顯示帳號、信箱、角色資訊,並多一個「進入後台」按鈕
🐛 遇到的問題與解決
問題:管理員登入後無法進入 Profile,因為 App.jsx 限制了 role="user"
解決:移除限制,讓所有登入用戶都能進入 Profile
💡 Day18 收穫