面试题答案
一键面试- 获取动态路由参数:
- 在SvelteKit中,你可以通过
$page.params
获取动态路由参数。假设路由定义为/user/[id]
,在组件脚本部分可以这样获取参数:
import { page } from '$app/stores'; import { derived } from 'svelte/store'; const userID = derived(page, ($page) => $page.params.id);
- 在SvelteKit中,你可以通过
- 从API获取相应用户数据:
- 利用
fetch
函数结合获取到的userID
从API获取数据。例如:
let userData; userID.subscribe((id) => { if (id) { fetch(`/api/users/${id}`) .then((response) => response.json()) .then((data) => { userData = data; }); } });
- 利用
- 处理参数缺失或无效情况:
- 参数缺失:
- 当
$page.params.id
不存在时,derived
中的id
值为undefined
。可以在获取数据逻辑中进行处理,比如显示一个提示信息。
{#if!$userID} <p>用户ID缺失,请检查链接。</p> {:else} <!-- 正常显示用户数据逻辑 --> {/if}
- 当
- 参数无效:
- 若API返回404或其他错误状态码表示参数无效(例如
id
格式不正确,API无法识别),可以在fetch
的then
处理中检查状态码。
userID.subscribe((id) => { if (id) { fetch(`/api/users/${id}`) .then((response) => { if (!response.ok) { throw new Error('无效的用户ID'); } return response.json(); }) .then((data) => { userData = data; }) .catch((error) => { console.error(error); // 显示错误提示 userData = null; const errorMessage = '获取用户数据失败:无效的用户ID'; }); } });
- 若API返回404或其他错误状态码表示参数无效(例如
- 在页面中可以这样显示错误信息:
{#if errorMessage} <p>{errorMessage}</p> {:else if userData} <!-- 显示用户数据 --> {/if}
- 参数缺失: