Files
school2-taro/src/pages/category/index.tsx
T
2026-08-11 10:53:06 +08:00

79 lines
2.3 KiB
TypeScript

import { View, Text } from '@tarojs/components'
import {Image, Loading, Space, Tag} from '@antmjs/vantui'
import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { getCategoryLinks } from '@/api/home'
import type { CategoryLinkItem } from '@/api/home'
import { navigateToLink } from '@/utils/navigate'
import './index.less'
export default function Category() {
const router = Taro.useRouter()
const categoryId = router.params.category_id || ''
const [links, setLinks] = useState<CategoryLinkItem[]>([])
const [loading, setLoading] = useState(true)
// 收到分类 ID 后请求该分类下的所有链接
useEffect(() => {
async function fetchCategoryLinks() {
try {
const res = await getCategoryLinks(Number(categoryId))
if (res.success && res.data) {
setLinks(
res.data
.filter((item) => item.status === 0)
.sort((a, b) => a.sort - b.sort)
)
}
} catch (err) {
console.warn('获取分类链接失败', err)
} finally {
setLoading(false)
}
}
if (categoryId) {
fetchCategoryLinks()
} else {
setLoading(false)
}
}, [categoryId])
return (
<View className='category'>
{/* 加载中 */}
{loading ? (
<View className='category-state'>
<Loading type='spinner'>加载中...</Loading>
</View>
) : links.length > 0 ? (
// 宫格链接(与首页宫格导航样式一致)
<View className='grid-wrapper'>
{links.map((item) => (
<View
className='grid-item'
key={item.id}
onClick={() => navigateToLink(item.link)}
>
<Image className='grid-item-image' src={item.image.preview_url}></Image>
<Text className='grid-item-title'>
<View>{item.title}</View>
<Space>
{ item.tag && item.tag.length > 0 && item.tag.map((tag, index) => (
<Tag type='danger' key={index}>{tag}</Tag>
))}
</Space>
</Text>
</View>
))}
</View>
) : (
// 空状态
<View className='category-state'>
<Text className='state-text'>暂无链接</Text>
</View>
)}
</View>
)
}