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

React入门问题:如何通过Link组件传递币种ID到详情路由页面

问题修复方案

1. 修正路由配置,给详情页传递路由props

你当前的Route写法没有把React Router提供的location等路由属性传给CoinDetails组件,导致拿不到Link传递的参数,修改App.js中/coinDetails对应的路由代码,二选一即可:

  • 写法1(使用component属性):
<Route path='/coinDetails' component={CoinDetails} />
  • 写法2(使用render属性,适合需要额外传自定义props的场景):
<Route path='/coinDetails' render={(routeProps) => <CoinDetails {...routeProps} />} />

2. 修正详情页参数获取和请求逻辑

你当前的请求代码存在参数取值错误、字符串拼接错误的问题,修改后的CoinDetails代码如下:

class CoinDetails extends React.Component {
  constructor(props){
    super(props);
    // 初始值设为空对象,避免渲染时访问属性报错
    this.state = {data : {}};
  }
  async getCoinData(){
    // 从路由state中拿到传递的uuid
    const uuid = this.props.location?.state?.uuid;
    // 没有uuid时提前返回,避免发起无效请求
    if(!uuid) return;
    // 正确拼接请求地址
    await fetch(`http://localhost:9000/coinDetails?uuid=${uuid}`)
    .then(response => response.json())
    .then(data => this.setState({data}))
  }
  componentDidMount(){
    this.getCoinData();
  };

  render(){
    return (
      <div>
        {/* 加加载状态判断,避免数据未返回时报错 */}
        <p>{this.state.data?.name || '数据加载中...'}</p>
      </div>
    )
  };
}

可选优化:使用路径参数传参更稳定

state传参在用户直接刷新详情页、或者手动输入地址访问详情页时会丢失参数,推荐改成路径参数的方式:

  1. 修改App.js路由定义:
<Route path='/coinDetails/:uuid' component={CoinDetails} />
  1. 主页面的Link改成直接拼接uuid到路径:
<Link to={`/coinDetails/${coin.uuid}`}>{coin.symbol}</Link>
  1. 详情页取参数的逻辑改成:
const uuid = this.props.match.params.uuid;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:27:04