面试题答案
一键面试1. Qwik 中动态路由的定义方式
在 Qwik 中,动态路由通过在路由路径中使用方括号 []
来定义。例如,假设你有一个用户详情页面,路由路径可以定义如下:
// 在 routes 目录下创建 [userId].qwik 页面组件
// 这个路径表示 userId 是一个动态参数
这样,[userId]
就是一个动态路由参数,不同的 userId
值会对应不同的用户详情页面。
2. 路由参数的捕获与处理
在 Qwik 页面组件中,可以通过 useRoute
钩子来捕获路由参数。示例如下:
import { component$, useRoute } from '@builder.io/qwik';
export default component$(() => {
const route = useRoute();
const userId = route.params.userId;
return <div>User ID: {userId}</div>;
});
在上述代码中,useRoute
钩子返回当前路由的信息,通过 route.params
可以获取到动态路由参数 userId
。
3. 不同页面组件间通过动态路由传递复杂数据结构(如对象)的方法
- URL 编码:可以将对象转换为 JSON 字符串,然后进行 URL 编码作为路由参数传递。在目标页面解码并还原对象。
- 发送方:
import { component$, navigate } from '@builder.io/qwik';
import { stringify } from 'querystring';
export default component$(() => {
const complexObject = { name: 'John', age: 30, hobbies: ['reading', 'coding'] };
const encodedObject = stringify({ data: JSON.stringify(complexObject) });
const handleClick = () => {
navigate(`/details?${encodedObject}`);
};
return <button onClick={handleClick}>Navigate with data</button>;
});
- 接收方:
import { component$, useLocation } from '@builder.io/qwik';
import { parse } from 'querystring';
export default component$(() => {
const location = useLocation();
const query = parse(location.search.slice(1));
const complexObject = JSON.parse(query.data as string);
return (
<div>
<p>Name: {complexObject.name}</p>
<p>Age: {complexObject.age}</p>
<p>Hobbies: {complexObject.hobbies.join(', ')}</p>
</div>
);
});
- 使用状态管理:可以使用 Qwik 的状态管理工具(如
createSignal
)在不同页面之间共享数据。例如,创建一个全局状态管理模块:- 创建状态管理模块:
import { component$, createSignal } from '@builder.io/qwik';
const sharedData = createSignal({});
export const setSharedData = (data: any) => {
sharedData.set(data);
};
export const getSharedData = () => {
return sharedData.get();
};
- 发送方:
import { component$, navigate } from '@builder.io/qwik';
import { setSharedData } from './sharedData';
export default component$(() => {
const complexObject = { name: 'John', age: 30, hobbies: ['reading', 'coding'] };
const handleClick = () => {
setSharedData(complexObject);
navigate('/details');
};
return <button onClick={handleClick}>Navigate with data</button>;
});
- 接收方:
import { component$ } from '@builder.io/qwik';
import { getSharedData } from './sharedData';
export default component$(() => {
const complexObject = getSharedData();
return (
<div>
<p>Name: {complexObject.name}</p>
<p>Age: {complexObject.age}</p>
<p>Hobbies: {complexObject.hobbies.join(', ')}</p>
</div>
);
});