1. 路由管理
设计思路
- 静态路由:Qwik支持静态路由,对于电商平台中如首页、商品列表页、商品详情页等常用页面,使用静态路由可以在构建时生成路由规则,提高首次加载速度。在
routes
目录下按照页面结构创建文件,例如routes/home.qwik
、routes/products/[productId].qwik
,这样Qwik能在编译时确定路由结构,无需在运行时动态解析。
- 路由懒加载:对于一些不常用的页面,如用户设置、订单历史等,可以采用路由懒加载的方式。当用户实际需要访问这些页面时,才加载对应的代码,减少首屏加载的代码体积。
关键代码片段
- 定义静态路由:在
routes
目录下创建文件,以商品详情页为例:
// routes/products/[productId].qwik
import { component$, useParams } from '@builder.io/qwik';
export default component$(() => {
const { productId } = useParams();
return (
<div>
<h1>Product Details: {productId}</h1>
{/* 商品详情展示代码 */}
</div>
);
});
- 路由懒加载:在
routes
目录下,对于需要懒加载的页面,使用动态导入:
// routes/settings.qwik
import { component$ } from '@builder.io/qwik';
const SettingsPage = () => import('./SettingsPage.qwik');
export default component$(() => {
return (
<div>
{/* 加载设置页面 */}
<SettingsPage />
</div>
);
});
2. 数据获取与缓存
设计思路
- SSR(服务器端渲染)与SSG(静态站点生成)结合:对于首页的热门商品推荐、导航栏信息等不经常变化的数据,使用SSG在构建时获取并生成静态页面。而对于用户特定的数据,如购物车数量、用户订单状态等,采用SSR在服务器端渲染时获取。
- 数据缓存:使用Qwik的
useStore
创建缓存机制。例如,当获取商品列表数据时,先检查缓存中是否有数据,如果有则直接使用缓存数据,避免重复请求。
关键代码片段
- SSG数据获取:在页面组件中使用
useLoaderData
获取构建时的数据,以首页热门商品推荐为例:
// routes/home.qwik
import { component$, useLoaderData } from '@builder.io/qwik';
export const loader = async () => {
const response = await fetch('https://api.example.com/top-products');
return response.json();
};
export default component$(() => {
const topProducts = useLoaderData();
return (
<div>
<h1>Top Products</h1>
{topProducts.map(product => (
<div key={product.id}>
<img src={product.imageUrl} alt={product.name} />
<p>{product.name}</p>
</div>
))}
</div>
);
});
import { component$, useStore } from '@builder.io/qwik';
const productCache = useStore({});
export default component$(() => {
const loadProduct = async (productId) => {
if (productCache[productId]) {
return productCache[productId];
}
const response = await fetch(`https://api.example.com/products/${productId}`);
const product = await response.json();
productCache[productId] = product;
return product;
};
return (
<div>
{/* 商品加载逻辑 */}
</div>
);
});
3. 组件优化
设计思路
- 组件拆分与懒加载:将大型组件拆分成多个小的、功能单一的组件。对于一些非首屏立即需要的组件,如商品详情页中的评论组件、相关推荐组件等,采用懒加载的方式。
- 使用
memo
优化:对于一些数据变化不频繁但渲染成本较高的组件,使用memo
来避免不必要的重新渲染。
关键代码片段
// routes/products/[productId].qwik
import { component$ } from '@builder.io/qwik';
const CommentsComponent = () => import('./CommentsComponent.qwik');
export default component$(() => {
return (
<div>
<h2>Comments</h2>
<CommentsComponent />
</div>
);
});
- 使用
memo
优化:假设我们有一个复杂的商品价格展示组件:
import { component$, memo } from '@builder.io/qwik';
const PriceDisplay = memo(({ price }) => {
return (
<div>
<p>Price: ${price}</p>
{/* 复杂的价格计算与展示逻辑 */}
</div>
);
});
export default component$(() => {
const productPrice = 100;
return (
<div>
<PriceDisplay price={productPrice} />
</div>
);
});