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传参在用户直接刷新详情页、或者手动输入地址访问详情页时会丢失参数,推荐改成路径参数的方式:
- 修改App.js路由定义:
<Route path='/coinDetails/:uuid' component={CoinDetails} />
- 主页面的Link改成直接拼接uuid到路径:
<Link to={`/coinDetails/${coin.uuid}`}>{coin.symbol}</Link>
- 详情页取参数的逻辑改成:
const uuid = this.props.match.params.uuid;
内容的提问来源于stack exchange,提问作者Maximus
相关产品推荐
相关产品推荐

