实现思路
- 定义动态路由参数类型:使用 TypeScript 的接口或类型别名来定义动态路由参数的结构。
- 嵌套路由配置类型:可以使用对象来表示嵌套路由结构,并为每个嵌套路由定义其对应的组件和参数类型。
- 类型安全的参数获取与传递:在组件中使用这些定义好的类型来确保参数获取和传递的类型安全。
关键代码示例
- 定义动态路由参数类型
// 定义用户 ID 参数类型
type UserIdParams = {
id: string;
};
// 定义用户详情页参数类型(继承自 UserIdParams)
type UserProfileParams = UserIdParams;
- 定义嵌套路由配置类型
// 定义嵌套路由结构类型
type NestedRouteConfig = {
path: string;
component: () => JSX.Element;
// 这里假设可以有子路由,所以定义一个可选的子路由数组
children?: NestedRouteConfig[];
};
// 示例嵌套路由配置
const userRoutes: NestedRouteConfig[] = [
{
path: '/user/:id',
component: () => <div>User Page</div>,
children: [
{
path: 'profile',
component: () => <div>User Profile Page</div>
}
]
}
];
- 在组件中使用类型安全的参数获取
import { createResource, createSignal } from 'solid-js';
import { useLocation } from 'solid-app-router';
const UserPage = () => {
const location = useLocation();
const { id } = location.params as UserIdParams;
// 这里假设通过 API 获取用户数据
const [user, setUser] = createSignal<any>();
createResource(() => `/api/user/${id}`, async (url) => {
const response = await fetch(url);
return response.json();
}, setUser);
return (
<div>
<h1>User {id}</h1>
{user() && <p>{user().name}</p>}
</div>
);
};
const UserProfilePage = () => {
const location = useLocation();
const { id } = location.params as UserProfileParams;
return (
<div>
<h1>User {id} Profile</h1>
</div>
);
};