面试题答案
一键面试- 安装依赖:
在Qwik项目目录下,通过npm或yarn安装
zustand
。- 使用npm:
npm install zustand
- 使用yarn:
yarn add zustand
- 创建Zustand store:
在项目合适的位置(例如
src/store
目录)创建一个store文件,比如counterStore.ts
。import create from 'zustand'; type CounterStore = { count: number; increment: () => void; decrement: () => void; }; const useCounterStore = create<CounterStore>((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), decrement: () => set((state) => ({ count: state.count - 1 })) })); export default useCounterStore;
- 在Qwik组件中使用该store:
在Qwik组件中导入创建好的store并使用。假设我们有一个
CounterComponent.tsx
组件。import { component$, useStore } from '@builder.io/qwik'; import useCounterStore from '../store/counterStore'; const CounterComponent = component$(() => { const counter = useStore(useCounterStore); return ( <div> <p>Count: {counter.count}</p> <button onClick={counter.increment}>Increment</button> <button onClick={counter.decrement}>Decrement</button> </div> ); }); export default CounterComponent;