返回

simple-redux-store 超简单 Redux Store 指南

前端

simple-redux-store 简介

simple-redux-store 是一个基于 React Hooks 与 Redux 的极简 Store 方案,适用于 Web 和 Node(SSR 环境)。它仅需 4 个对象,2 个用于配置全局状态,2 个用于读取和更新状态。simple-redux-store 简单易用,可以帮助你轻松管理状态,掌控全局数据。

simple-redux-store 特点

  • 简单 :simple-redux-store 只有 4 个对象,简单易学,易于使用。
  • 通用 :simple-redux-store 适用于 Web 和 Node(SSR 环境),可以在任何项目中使用。
  • 高效 :simple-redux-store 性能优异,可以高效地管理状态。
  • 可扩展 :simple-redux-store 可扩展性强,可以根据需要添加更多功能。

simple-redux-store 使用方法

安装

npm install simple-redux-store

初始化 Store

import { createStore } from 'simple-redux-store';

const store = createStore({
  // 初始状态
  state: {
    count: 0,
  },

  // 提交事务
  mutations: {
    increment(state) {
      state.count++;
    },
  },
});

获取状态

import { useStore } from 'simple-redux-store';

const App = () => {
  // 使用 `useStore` 获取 store 的状态
  const count = useStore().state.count;

  // 返回组件
  return <h1>Count: {count}</h1>;
};

更新状态

import { useStore } from 'simple-redux-store';

const App = () => {
  // 使用 `useStore` 获取 store 的状态
  const store = useStore();

  // 使用 `commit` 更新 store 的状态
  const incrementCount = () => {
    store.commit('increment');
  };

  // 返回组件
  return (
    <>
      <h1>Count: {store.state.count}</h1>
      <button onClick={incrementCount}>Increment</button>
    </>
  );
};

更多用法

simple-redux-store 还有更多用法,例如:

  • 在 Node 中使用
  • 使用中间件
  • 创建自定义 Store

更多用法请参考 simple-redux-store 的文档。

总结

simple-redux-store 是一个简单易用、通用高效、可扩展性强的 Store 方案,非常适合 React 和 Redux 项目。如果你正在寻找一个轻量级的 Store 方案,simple-redux-store 是一个不错的选择。