面试题答案
一键面试- 安装:
- 在Qwik项目的根目录下,通过npm或yarn安装Zustand。
- 使用npm:
npm install zustand
- 使用yarn:
yarn add zustand
- 初始化:
- 在项目中创建一个Zustand的store文件,例如
store.ts
。 - 引入
create
函数,示例代码如下:
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;
- 在项目中创建一个Zustand的store文件,例如
- 在组件中使用Zustand的状态管理功能:
- 在Qwik组件中引入创建好的store。
- 以使用上述
useCounterStore
为例,假设在一个Counter.qwik
组件中:
import { component$, useStore } from '@builder.io/qwik'; import useCounterStore from './store'; const Counter = component$(() => { const { count, increment, decrement } = useStore(useCounterStore); return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> </div> ); }); export default Counter;
- 这里通过
useStore
钩子来连接Zustand的store到Qwik组件,从而可以在组件中使用store的状态和方法。