Rematch 开源项目教程
1、项目介绍
Rematch 是一个基于 Redux 的最佳实践框架,旨在简化 Redux 的使用,减少样板代码,并提供更强大的功能。Rematch 通过内置的异步处理、TypeScript 支持、插件系统等功能,使得 Redux 的使用变得更加简单和高效。
2、项目快速启动
安装 Rematch
首先,你需要在你的项目中安装 Rematch:
npm install @rematch/core
创建 Store
接下来,创建一个简单的 Rematch store:
import { init } from '@rematch/core';
const count = {
state: 0, // 初始状态
reducers: {
increment(state, payload) {
return state + payload;
},
},
effects: (dispatch) => ({
async incrementAsync(payload, rootState) {
await new Promise((resolve) => setTimeout(resolve, 1000));
dispatch.count.increment(payload);
},
}),
};
const store = init({
models: { count },
});
export default store;
使用 Store
在你的应用中使用这个 store:
import React from 'react';
import { Provider, connect } from 'react-redux';
import store from './store';
const mapState = (state) => ({
count: state.count,
});
const mapDispatch = (dispatch) => ({
increment: () => dispatch.count.increment(1),
incrementAsync: () => dispatch.count.incrementAsync(1),
});
const App = connect(mapState, mapDispatch)(({ count, increment, incrementAsync }) => (
<div>
<h1>{count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={incrementAsync}>Increment Async</button>
</div>
));
const Root = () => (
<Provider store={store}>
<App />
</Provider>
);
export default Root;
3、应用案例和最佳实践
应用案例
Rematch 可以用于各种前端框架,如 React、Angular 和 Vue。以下是一个简单的 React 应用案例:
import React from 'react';
import { Provider, connect } from 'react-redux';
import { init } from '@rematch/core';
const count = {
state: 0,
reducers: {
increment(state, payload) {
return state + payload;
},
},
effects: (dispatch) => ({
async incrementAsync(payload, rootState) {
await new Promise((resolve) => setTimeout(resolve, 1000));
dispatch.count.increment(payload);
},
}),
};
const store = init({
models: { count },
});
const mapState = (state) => ({
count: state.count,
});
const mapDispatch = (dispatch) => ({
increment: () => dispatch.count.increment(1),
incrementAsync: () => dispatch.count.incrementAsync(1),
});
const App = connect(mapState, mapDispatch)(({ count, increment, incrementAsync }) => (
<div>
<h1>{count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={incrementAsync}>Increment Async</button>
</div>
));
const Root = () => (
<Provider store={store}>
<App />
</Provider>
);
export default Root;
最佳实践
- 模块化管理:将不同的业务逻辑拆分成不同的模块,便于管理和维护。
- 异步处理:使用
effects
处理异步操作,避免在组件中处理复杂的异步逻辑。 - TypeScript 支持:利用 TypeScript 的类型检查和自动补全功能,提高代码的可维护性和可读性。
4、典型生态项目
官方插件
- @rematch/loading:自动管理加载状态。
- @rematch/persist:持久化存储状态。
- @rematch/select:提供更强大的状态选择功能。
社区插件
- @rematch/immer:使用 Immer 简化不可变状态管理。
- @rematch/updated:自动跟踪状态的更新。
通过这些插件,你可以进一步扩展 Rematch 的功能,满足不同的业务需求。