day12-03.详情模块
路由跳转传参
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>
获取详情数据
import { http } from '@/utils'
import { ResType } from './shared'
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}`,
})
}
import { NavBar } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { DetailRes, fetchDetailAPI } from '@/apis/detail'
import { useNavigate, useSearchParams } from 'react-router-dom'
const Detail = () => {
const [detail, setDetail] = useState<DetailRes | null>(null)
const [params] = useSearchParams()
const id = params.get('id')
useEffect(() => {
async function getDetail() {
try {
const res = await fetchDetailAPI(id!)
setDetail(res.data.data)
} catch (error) {
throw new Error('fetch detail error')
}
}
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
Last updated
Was this helpful?