跳到主要内容

语法

2025年04月11日
柏拉文
越努力,越幸运

一、最佳实践


1.1 定义 Counter Store

import { create } from "zustand";

interface CounterState {
count: number;
add: () => void;
min: () => void;
set: (value: number) => void;
}

export const useCounterStore = create<CounterState>((set) => {
return {
count: 0,
add: () => {
return set((state) => {
return {
count: state.count + 1,
};
});
},
min: () => {
return set((state) => {
return {
count: state.count - 1,
};
});
},
set: (value: number) => {
return set(() => {
return {
count: value,
};
});
},
};
});

1.2 使用 Counter Store

import { useCounterStore } from "./store/zustand/counter";

const App = () => {
const add = useCounterStore((state) => state.add);
const min = useCounterStore((state) => state.min);
const set = useCounterStore((state) => state.set);
const count = useCounterStore((state) => state.count);

const handleAdd = () => {
add();
};

const handleMin = () => {
min();
};

const handleSet = () => {
set(10);
};

return (
<div>
<h1>{count}</h1>

<button onClick={() => handleAdd()}>增加</button>
<button onClick={() => handleMin()}>减少</button>
<button onClick={() => handleSet()}>设置</button>
</div>
);
};

export default App;