面试题答案
一键面试实现思路
- 状态管理:使用Qwik的
$
符号定义响应式状态来存储购物车数据。这样,当数据发生变化时,依赖该状态的组件会自动重新渲染。 - 共享状态:为了确保多个页面之间共享购物车数据,可以将购物车状态提升到更高层级的组件(如应用的根组件),或者使用类似于
useContext
的机制在不同组件间传递状态。 - 路由机制:利用Qwik的路由系统,在页面切换时确保新页面能获取到最新的购物车数据。可以在路由变化的钩子函数中更新页面状态,使其反映最新的购物车数据。
代码示例
- 定义购物车状态:
import { component$, useState$ } from '@builder.io/qwik';
// 商品对象类型定义
type Product = {
name: string;
price: number;
quantity: number;
};
const ShoppingCart = component$(() => {
// 购物车状态
const [cart$, setCart$] = useState$<Product[]>([]);
// 修改商品数量的函数
const updateQuantity = (productIndex: number, newQuantity: number) => {
const newCart = [...cart$];
newCart[productIndex].quantity = newQuantity;
setCart$(newCart);
};
return (
<div>
{/* 购物车列表渲染 */}
{cart$.map((product, index) => (
<div key={index}>
<p>{product.name}</p>
<p>Price: ${product.price}</p>
<input
type="number"
value={product.quantity}
onChange={(e) => {
const newQuantity = parseInt(e.target.value, 10);
updateQuantity(index, newQuantity);
}}
/>
</div>
))}
</div>
);
});
export default ShoppingCart;
- 在多个页面共享状态:
- 根组件(假设为
App.tsx
):
- 根组件(假设为
import { component$, useContext$ } from '@builder.io/qwik';
import { Router } from '@builder.io/qwik-city';
import ShoppingCart from './ShoppingCart';
// 创建上下文用于共享购物车状态
const CartContext = createContext$<{ cart$: ReturnType<typeof useState$<Product[]>> }>({
cart$: useState$<Product[]>([])
});
const App = component$(() => {
const { cart$ } = useContext$(CartContext);
return (
<div>
<CartContext.Provider value={{ cart$ }}>
<Router />
</CartContext.Provider>
</div>
);
});
export default App;
- 其他页面获取购物车状态:
import { component$, useContext$ } from '@builder.io/qwik';
import { CartContext } from './App';
const AnotherPage = component$(() => {
const { cart$ } = useContext$(CartContext);
return (
<div>
<h1>Another Page</h1>
{/* 展示购物车数据 */}
{cart$.map((product, index) => (
<div key={index}>
<p>{product.name}</p>
<p>Quantity: {product.quantity}</p>
</div>
))}
</div>
);
});
export default AnotherPage;
- 利用路由机制更新状态:
- 在路由变化钩子函数中更新:
import { component$, useContext$, onRouteChange$ } from '@builder.io/qwik';
import { CartContext } from './App';
const SomePage = component$(() => {
const { cart$ } = useContext$(CartContext);
onRouteChange$(({ to }) => {
// 这里可以根据路由变化逻辑更新购物车数据
// 例如从服务器重新获取最新购物车数据
// 假设这里只是简单打印路由变化信息
console.log(`Routing to ${to}`);
});
return (
<div>
<h1>Some Page</h1>
{/* 展示购物车数据 */}
{cart$.map((product, index) => (
<div key={index}>
<p>{product.name}</p>
<p>Quantity: {product.quantity}</p>
</div>
))}
</div>
);
});
export default SomePage;
这样,通过上述状态管理和路由机制的结合,当购物车中商品数量在某个页面修改后,其他相关页面的购物车数据也能实时同步更新。