面试题答案
一键面试- 处理动态参数:
- 在Qwik的路由组件中,可以通过
useRouteParams
钩子函数获取动态参数。例如,在商品详情页组件中:
import { component$, useRouteParams } from '@builder.io/qwik'; export default component$(() => { const { productId } = useRouteParams(); return ( <div> {/* 后续使用productId进行API请求 */} </div> ); });
- 在Qwik的路由组件中,可以通过
- 发起API请求:
- 使用
fetch
API来向后端发起请求。可以在组件的useEffect$
钩子中进行,这样在组件渲染时触发请求。
import { component$, useRouteParams, useEffect$ } from '@builder.io/qwik'; import type { Product } from './types'; export default component$(() => { const { productId } = useRouteParams(); const [product, setProduct] = useState<Product | null>(null); useEffect$(async () => { if (productId) { const response = await fetch(`/api/products/${productId}`); if (response.ok) { const data = await response.json(); setProduct(data); } } }, [productId]); return ( <div> {product? ( <div> {/* 展示商品数据 */} <p>{product.name}</p> <p>{product.price}</p> </div> ) : ( <p>Loading...</p> )} </div> ); });
- 使用
- 处理加载错误:
- 在
fetch
请求时捕获可能出现的错误。可以通过try - catch
块来处理。
import { component$, useRouteParams, useEffect$ } from '@builder.io/qwik'; import type { Product } from './types'; export default component$(() => { const { productId } = useRouteParams(); const [product, setProduct] = useState<Product | null>(null); const [error, setError] = useState<string | null>(null); useEffect$(async () => { try { if (productId) { const response = await fetch(`/api/products/${productId}`); if (response.ok) { const data = await response.json(); setProduct(data); } else { setError('Failed to load product data'); } } } catch (e) { setError('An error occurred while loading product data'); } }, [productId]); return ( <div> {error? ( <p>{error}</p> ) : product? ( <div> {/* 展示商品数据 */} <p>{product.name}</p> <p>{product.price}</p> </div> ) : ( <p>Loading...</p> )} </div> ); });
- 在
这样,通过以上步骤,在Qwik应用的商品详情页中可以处理动态参数、发起API请求并处理加载错误。