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

React路由如何根据访问路径匹配展示对应加密货币的详情信息

实现步骤

1. 调整路由配置

给币种详情页的路由规则添加动态参数占位符,以React Router v6为例:

import { Routes, Route } from 'react-router-dom'
import CoinList from './CoinList'
import CoinPage from './CoinPage'

function App() {
  return (
    <Routes>
      <Route path="/" element={<CoinList />} />
      {/* 新增带动态参数:symbol的路由规则 */}
      <Route path="/:symbol" element={<CoinPage />} />
    </Routes>
  )
}

2. 修改CoinPage组件逻辑

通过路由钩子获取路径中的币种符号,再从币种数组中匹配对应数据渲染:

import { useParams } from 'react-router-dom'
// 替换为你实际存放币种数组的文件路径
import users from './coins.js'

function CoinPage() {
  // 获取路径中传递的symbol参数
  const { symbol } = useParams()
  // 从币种数组中匹配symbol一致的对应数据
  const currentCoin = users.find(coin => coin.symbol === symbol)

  // 异常处理:访问不存在的币种符号时的提示
  if (!currentCoin) {
    return <div className="bg-gray-800 w-56 h-56 text-white p-4 rounded-2xl mt-12">未查询到对应币种信息</div>
  }

  return (
    <div className="bg-gray-800 w-56 h-56 text-white p-4 rounded-2xl mt-12">
      <p>{currentCoin.name}</p>
      <p>{currentCoin.price_usd}</p>
      <!-- 可自行扩展展示rank、nameid等其他字段 -->
    </div>
  )
}

实现原理

你之前固定写死了users[0]所以只会展示第一条比特币的信息,修改后通过useParams拿到路由路径中的币种符号参数,再用find方法从数组中筛选出对应币种的数据渲染即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:39:01