面试题答案
一键面试useStore的作用
在Qwik应用中,useStore
用于创建可响应式的存储。它使得应用状态能够在组件间共享,并且当状态发生变化时,相关组件会自动重新渲染,确保状态的一致性和数据的正确显示。
计数器功能实现
- 导入相关模块:
import { component$, useStore } from '@builder.io/qwik';
- 创建计数器存储:
const Counter = component$(() => {
const store = useStore({ count: 0 });
const increment = () => {
store.count++;
};
return (
<div>
<p>Count: {store.count}</p>
<button onClick={increment}>Increment</button>
</div>
);
});
在上述代码中,通过 useStore
创建了一个包含 count
初始值为 0
的存储对象。increment
函数用于增加 count
的值,每次点击按钮,store.count
变化,组件会重新渲染以正确显示更新后的值。