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

React页面间参数传递问题:如何获取作曲家详情?

解决方案

1. 修正路由组件匹配问题

你的路由配置中,详情页路由/api/composers/:id对应的组件是<ComposerMongodb />,但实际详情页组件是Profile,这会导致跳转后无法渲染正确页面。需修改路由:

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/api/composers" element={<Composer />} />
  <Route path="/api/composers/:id" element={<Profile />} /> {/* 替换为Profile组件 */}
</Routes>

2. 正确提取路由参数

路由中定义的参数是:id,因此在Profile组件中要通过useParams解构id,而非_id:

const { id } = useParams(); // 匹配路由中的:id参数

3. 添加详情数据请求逻辑

在Profile组件中,通过useEffect钩子,利用获取到的id调用后端接口加载作曲家详情,并处理状态更新:

import React, { useState, useEffect } from "react";
import Card from "../../Card";
import "./Composer.css";
import { useParams } from "react-router";

const Profile = () => {
  const [composer, setComposer] = useState(null); // 单个作曲家详情,无需数组
  const [isLoading, setIsLoading] = useState(false);

  const { id } = useParams();

  useEffect(() => {
    setIsLoading(true);
    const fetchComposerDetail = async () => {
      try {
        const result = await fetch(`http://localhost:3000/api/composer/${id}`); // 对应后端接口路径
        const resultJson = await result.json();
        setComposer(resultJson);
      } catch (error) {
        console.error("加载作曲家详情失败:", error);
      } finally {
        setIsLoading(false);
      }
    };

    if (id) { // 确保id存在时发起请求
      fetchComposerDetail();
    }
  }, [id]); // 依赖id,参数变化时重新请求

  if (isLoading) {
    return (
      <div className="loading">
        <p>...loading</p>
      </div>
    );
  }

  if (!composer) {
    return <div>未找到该作曲家</div>;
  }

  return (
    <div className="albums-container">
      <Card className="albums-card">
        <img
          src={composer.image || "https://via.placeholder.com/168x118.png"}
          alt={`${composer.name} thumbnail`}
        />
        <h5>{composer.name}</h5>
        <h6>{composer.nationality}</h6>
        <p>{composer.description}</p> {/* 渲染描述信息 */}
      </Card>
    </div>
  );
};

export default Profile;

4. 优化列表页Link传参(可选)

如果需要临时传递更多数据,可以优化state的传递方式(但建议优先以接口返回数据为准):

<Link
  to={{
    pathname: `/api/composers/${album._id}`,
    state: { composerId: album._id, name: album.name } // 传递对象而非字符串
  }}
  key={album._id} // 用唯一的_id作为key,避免重复
  style={{ textDecoration: "none", color: "black" }}
>
  {/* 原有Card内容 */}
</Link>

内容的提问来源于stack exchange,提问作者Lucas R.G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 03:11:52