路由跳转传参
tsx
const navigateToDetail = (id: string) => {
navigate(`/detail?id=${id}`)
}
<List.Item
key={item.art_id}
onClick={() => navigateToDetail(item.art_id)}
arrow={false}
>
{item.title}
</List.Item>
获取详情数据
实现步骤
- 创建API接口函数
- 实现页面导航
- 渲染文章内容
typescript
import { http } from '@/utils'
import { ResType } from './type'
export type DetailRes = {
art_id: string
title: string
pubdate: string
content: string
}
export function fetchDetailAPI(article_id: string) {
return http.request<ResType<DetailRes>>({
url: `/articles/${article_id}`,
})
}
tsx
// ... existing code ...
import { NavBar } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { DetailRes, fetchDetailAPI } from '@/apis/detail'
import { useNavigate, useSearchParams } from 'react-router-dom'
/**
* 详情页面组件
* 根据URL参数中的id获取并展示详情信息
*/
const Detail = () => {
// 存储详情数据的状态
const [detail, setDetail] = useState<DetailRes | null>(null)
// 获取URL查询参数
const [params] = useSearchParams()
// 从查询参数中提取id
const id = params.get('id')
// 组件挂载时根据id获取详情数据
useEffect(() => {
/**
* 异步获取详情数据
* @throws {Error} 获取详情失败时抛出错误
*/
async function getDetail() {
try {
const res = await fetchDetailAPI(id!)
setDetail(res.data.data)
} catch (error) {
throw new Error('fetch detail error')
}
}
// 如果存在id则获取详情数据
if (id) {
getDetail()
}
}, [id])
// 获取路由导航函数
const navigate = useNavigate()
// 返回上一页
const back = () => navigate(-1)
// 数据未加载完成时显示加载提示
if (!detail) {
return <div>this is loading</div>
}
// 渲染详情内容
return (
<div>
<NavBar onBack={back}>{detail.title}</NavBar>
<div dangerouslySetInnerHTML={{ __html: detail.content }}></div>
</div>
)
}
export default Detail
// ... existing code ...