You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS参数传递:主从数据页面导航实现疑问

Alright, let's get your React master-detail navigation working perfectly. You’ve already got the list page set up with NavLink to jump to details, so let’s tie all the pieces together step by step.

Master-Detail Navigation in React: Full Implementation

1. First, Lock in Your Routing Setup

Assuming you’re using React Router v6 (the current standard), you need to define both your list route and the dynamic details route in your root router file (like App.js or Routes.js). This tells React Router how to map URLs to components:

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import DataList from './DataList'; // Your existing list component
import Details from './Details'; // Your details page component

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<DataList />} />
        {/* The :dataId part is a dynamic parameter that will match any value in the URL */}
        <Route path="/details/:dataId" element={<Details />} />
      </Routes>
    </Router>
  );
}

export default App;

2. Polish Your List (Master) Component

Your existing list code is solid, but we can make the NavLink path a bit cleaner with template literals. Also, adding active styling helps users keep track of which item they came from:

import { NavLink } from 'react-router-dom';

function DataList({ myDataList }) {
  return (
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Description</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        {myDataList.map(myData => (
          <tr key={myData.dataId}>
            <td>{myData.dataId}</td>
            <td>{myData.dataDescription}</td>
            <td>
              {/* Clean up the path with template literals */}
              <NavLink 
                to={`/details/${myData.dataId}`}
                className={({ isActive }) => isActive ? 'active-link' : ''}
              >
                Details
              </NavLink>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

export default DataList;

Add this CSS for the active link (put it in your global styles or component CSS):

.active-link {
  color: #007bff;
  font-weight: 600;
  text-decoration: underline;
}

3. Build Out the Details Page (Using Your VS Template)

You mentioned using the VS example template's DetailsStat interface—let’s integrate that with fetching the dataId from the URL and displaying the corresponding data. Here’s how to pull it all together:

import { useParams, NavLink } from 'react-router-dom';
import { useState, useEffect } from 'react';

// Your VS template's interface (adjust fields to match your data)
interface DetailsStat {
  dataId: number;
  dataDescription: string;
  createdAt: string;
  status: string;
  // Add any other fields your detail view needs
}

function Details() {
  // Grab the dataId from the URL parameters (it'll be a string by default)
  const { dataId } = useParams<{ dataId: string }>();
  const [detailData, setDetailData] = useState<DetailsStat | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    // Fetch the detail data when the dataId changes
    const fetchDetails = async () => {
      if (!dataId) return;

      try {
        setLoading(true);
        // Replace this with your actual API endpoint
        const response = await fetch(`/api/data/${Number(dataId)}`);
        if (!response.ok) throw new Error('Failed to load details');
        
        const data: DetailsStat = await response.json();
        setDetailData(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Something went wrong');
      } finally {
        setLoading(false);
      }
    };

    fetchDetails();
  }, [dataId]);

  // Handle loading, error, and empty states
  if (loading) return <div className="details-loading">Loading details...</div>;
  if (error) return <div className="details-error">Oops: {error}</div>;
  if (!detailData) return <div className="details-empty">No data found for this ID</div>;

  return (
    <div className="details-container">
      <h1>Data Details: ID {detailData.dataId}</h1>
      
      <div className="detail-section">
        <h3>Description</h3>
        <p>{detailData.dataDescription}</p>
      </div>

      <div className="detail-section">
        <h3>Created Date</h3>
        <p>{new Date(detailData.createdAt).toLocaleDateString()}</p>
      </div>

      <div className="detail-section">
        <h3>Status</h3>
        <p>{detailData.status}</p>
      </div>

      {/* Add a back link to return to the list */}
      <NavLink to="/" className="back-link">← Back to Data List</NavLink>
    </div>
  );
}

export default Details;

Quick Tips to Avoid Headaches

  • Type Safety: If you’re using TypeScript, remember URL params are strings—convert dataId to a number with Number(dataId) if your API expects a numeric ID.
  • Error Handling: Always show loading/error states—users hate staring at blank pages!
  • Unique Keys: You’re already using myData.dataId as the key in your map—great call, that’s the best practice for list items.

内容的提问来源于stack exchange,提问作者Paul Michaels

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:45:05