没有样板代码,没有额外学习成本,简单清晰,上手即用。
https://www.npmjs.com/package/zustand
定义:
import { create } from "zustand";
type SidebarStore = {
isOpen: boolean;
onOpen: () => void;
onClose: () => void;
};
export const useSidebar = create<SidebarStore>((set) => ({
isOpen: false,
onOpen: () => set({ isOpen: true }),
onClose: () => set({ isOpen: false }),
}));
在 React 组件中使用:
const onOpen = useSidebar((state) => state.onOpen);
const onClose = useSidebar((state) => state.onClose);
const isOpen = useSidebar((state) => state.isOpen);