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
相关产品推荐
相关产品推荐

