react 中的Zustand的store使用

这个react 中的store 就跟vue中的pinia 是差不多的使用方法

  • create<ThemeState>:创建一个 Zustand store,并用 TypeScript 接口约束 store 的形状。

  • (set) => ({ ... }) :回调函数,set 用于更新状态。

  • 返回值 :对象包含状态theme)和修改状态的方法setThemetoggleTheme)。

    • setTheme:直接设置新主题。set({ theme }) 会合并新状态。

    • toggleTheme:基于当前状态切换。set((state) => ({ theme: ... })) 使用函数式更新。

      import { create } from 'zustand';

      type Theme = 'light' | 'dark';

      interface ThemeState {
      theme: Theme;
      setTheme: (theme: Theme) => void;
      toggleTheme: () => void;
      }

      export const useThemeStore = create<ThemeState>((set) => ({
      theme: 'light',
      setTheme: (theme) => set({ theme }),
      toggleTheme: () => set((state) => ({ theme: state.theme === 'light' ? 'dark' : 'light' })),
      }));

store 文件放在 src/store/useThemeStore.ts

组件中使用:

复制代码
// src/pages/Home.tsx
import { useThemeStore } from '../store/useThemeStore';

function Home() {
  // 解构出 state 和 actions
  const { theme, setTheme, toggleTheme } = useThemeStore();

  return (
    <div style={{ background: theme === 'dark' ? '#333' : '#fff' }}>
      <p>Current theme: {theme}</p>
      <button onClick={() => setTheme('light')}>Light</button>
      <button onClick={() => setTheme('dark')}>Dark</button>
      <button onClick={toggleTheme}>Toggle</button>
    </div>
  );
}

export default Home;

也可以这样写 优化

复制代码
function ShowTheme() {
  const theme = useThemeStore((state) => state.theme);
  return <div>Theme: {theme}</div>;
}

function ThemeControls() {
  const setTheme = useThemeStore((state) => state.setTheme);
  const toggleTheme = useThemeStore((state) => state.toggleTheme);
  return (
    <>
      <button onClick={() => setTheme('light')}>Light</button>
      <button onClick={toggleTheme}>Toggle</button>
    </>
  );
}

因为 Zustand 的 store 是在 React 外部创建的全局单例,通过 create 返回的 hook 会订阅这个单例的变化,所以不需要 Context。

这个就跟vue 的一模一样的 当然这个是不分模块的写法

我们如果项目庞大 需要分模块 就需要跟vue开发一样了需要分模块

相关推荐
我命由我123452 小时前
Vue3 开发中,字符串中的 <br\> 标签被直接当作文本显示出来了,而不是被解析为 HTML 换行标签
开发语言·前端·javascript·vue.js·html·ecmascript·html5
亿元程序员2 小时前
Cocos4开源都快半年了,还有不会用官方MCP的?安排!
前端
早點睡3902 小时前
ReactNative项目OpenHarmony三方库集成实战:react-native-inappbrowser(也可以考虑WebView)
javascript·react native·react.js
北风toto2 小时前
Vue多文件学习项目综合案例——面经基础版,黑马vue教程
javascript·vue.js·学习
奔跑的呱呱牛3 小时前
xlsx 已停止维护且存在漏洞!推荐一个可直接替代的 npm 库
前端·npm·node.js·xlsx·sheetjs
珑墨3 小时前
pnpm 与 node_modules:硬链接、软连接(符号链接)、Junction 速记
前端
浪扼飞舟3 小时前
WPF输入验证(ValidationRule)
java·javascript·wpf
freewlt3 小时前
Monorepo 架构下的前端工程化实践:pnpm + Turborepo 从入门到落地
前端·arcgis·架构
徐小夕11 小时前
我用 AI 撸了个开源"万能预览器":浏览器直接打开 Office、CAD 和 3D 模型
前端·vue.js·github