Redux Orchestrate 使用教程
项目介绍
Redux Orchestrate 是一个简单的 Redux 中间件,旨在替代 redux-saga 或 redux-observable。它通过一个简单的配置对象来定义大多数常见操作,而不是使用生成器或 Observables。Redux Orchestrate 提倡“瘦动作,胖 reducer”的理念,通过将 reducer 分解成更小的部分(称为 event)来简化状态更新逻辑。
项目快速启动
安装
首先,通过 npm 安装 Redux Orchestrate:
npm install --save redux-orchestrate
使用
以下是一个简单的计数器示例,展示如何使用 Redux Orchestrate:
// store.js
import { createStore, applyMiddleware } from 'redux';
import orchestrate from 'redux-orchestrate';
// 定义 reducer
const reducer = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
};
// 配置 orchestrate
const orchestrateConfig = {
INCREMENT: (state) => state + 1,
DECREMENT: (state) => state - 1,
};
// 创建 store
const store = createStore(
reducer,
applyMiddleware(orchestrate(orchestrateConfig))
);
export default store;
在 React 中使用
如果你使用 React,还需要安装 react-redux
:
npm install --save react-redux
然后,将 store 连接到你的 React 组件:
// App.js
import React from 'react';
import { Provider, connect } from 'react-redux';
import store from './store';
const App = ({ count, increment, decrement }) => (
<div>
<h1>{count}</h1>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
const mapStateToProps = (state) => ({
count: state,
});
const mapDispatchToProps = (dispatch) => ({
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' }),
});
const ConnectedApp = connect(mapStateToProps, mapDispatchToProps)(App);
const Root = () => (
<Provider store={store}>
<ConnectedApp />
</Provider>
);
export default Root;
应用案例和最佳实践
计数器应用
上述快速启动部分已经展示了如何使用 Redux Orchestrate 实现一个简单的计数器应用。这个示例展示了如何通过配置对象来定义状态更新逻辑,而不是使用复杂的生成器或 Observables。
异步操作
Redux Orchestrate 也可以处理异步操作。以下是一个简单的异步操作示例:
// store.js
import { createStore, applyMiddleware } from 'redux';
import orchestrate from 'redux-orchestrate';
import thunk from 'redux-thunk';
const reducer = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT_ASYNC':
return state + 1;
default:
return state;
}
};
const orchestrateConfig = {
INCREMENT_ASYNC: (state) => state + 1,
};
const store = createStore(
reducer,
applyMiddleware(thunk, orchestrate(orchestrateConfig))
);
export default store;
// actions.js
export const incrementAsync = () => (dispatch) => {
setTimeout(() => {
dispatch({ type: 'INCREMENT_ASYNC' });
}, 1000);
};
// App.js
import React from 'react';
import { Provider, connect } from 'react-redux';
import store from './store';
import { incrementAsync } from './actions';
const App = ({ count, incrementAsync }) => (
<div