Spring+React项目中,根据用户数量动态生成个人主页跳转按钮
Got it, let's work through this together! Since you're building a React + Spring app and need to generate dynamic profile buttons for your user data, here's a straightforward solution tailored to your needs:
First, make sure you have react-router-dom set up (it's the standard for navigation in React apps). If you haven't installed it yet, run this command in your React project:
npm install react-router-dom # or yarn add react-router-dom
Option 1: Use React Router's Link Component (Recommended)
This is the best practice for single-page app navigation, as it avoids full page reloads. Here's a complete component example:
import { Link } from 'react-router-dom'; import { useState, useEffect } from 'react'; function UserProfileButtons() { // State to store your fetched user data const [users, setUsers] = useState([]); // Fetch user data from your Spring backend useEffect(() => { async function fetchUsers() { try { // Replace with your actual Spring API endpoint const response = await fetch('/api/filtered-users'); const userData = await response.json(); setUsers(userData); } catch (err) { console.error('Failed to fetch users:', err); } } fetchUsers(); }, []); return ( <div className="user-buttons-container"> <h3>Filtered Users</h3> {/* Map over each user to generate a profile link */} {users.map((userEntry, index) => { // Extract the username from your JSON structure (adjust if needed) const username = userEntry.user.attributes.firstname; const profileUrl = `/profile/${username}`; // Use a unique key (prefer a user ID over index if your API returns one) return ( <Link key={index} to={profileUrl} className="profile-button" style={{ display: 'block', margin: '10px 0', padding: '8px 16px', backgroundColor: '#2563eb', color: 'white', textDecoration: 'none', borderRadius: '4px', width: 'fit-content' }} > View {username}'s Profile </Link> ); })} </div> ); } export default UserProfileButtons;
Option 2: Use a Button with useNavigate Hook
If you specifically need a button element instead of a link, use React Router's useNavigate hook to handle navigation on click:
import { useNavigate } from 'react-router-dom'; import { useState, useEffect } from 'react'; function UserProfileButtons() { const [users, setUsers] = useState([]); const navigate = useNavigate(); useEffect(() => { // Same fetch logic as above async function fetchUsers() { try { const response = await fetch('/api/filtered-users'); const userData = await response.json(); setUsers(userData); } catch (err) { console.error('Failed to fetch users:', err); } } fetchUsers(); }, []); const goToProfile = (username) => { navigate(`/profile/${username}`); }; return ( <div className="user-buttons-container"> <h3>Filtered Users</h3> {users.map((userEntry, index) => { const username = userEntry.user.attributes.firstname; return ( <button key={index} onClick={() => goToProfile(username)} style={{ margin: '10px 0', padding: '8px 16px', cursor: 'pointer', backgroundColor: '#2563eb', color: 'white', border: 'none', borderRadius: '4px' }} > View {username}'s Profile </button> ); })} </div> ); } export default UserProfileButtons;
Important Notes:
- Unique Keys: If your Spring API returns a unique user ID (like
idin the user object), use that instead ofindexfor thekeyprop — it helps React update the DOM more efficiently. - Username Extraction: In your JSON example, the username is in
user.attributes.firstname. If your actual data uses a different field (likeusernamedirectly or the prefix of the principal email), adjust that line accordingly (e.g.,const username = userEntry.user.principal.split('@')[0];to get "cat" from "cat@sitter.com"). - Spring Backend Setup: Ensure your Spring app is correctly exposing the filtered user data at your chosen endpoint, and that your React app is configured to proxy requests to the Spring server (add
"proxy": "http://localhost:8080"to your Reactpackage.jsonif Spring runs on port 8080).
内容的提问来源于stack exchange,提问作者Jakeeln
相关产品推荐
相关产品推荐

