sim-react-redux
简化版的 react-redux !
特点&目标
- 以最简洁的方式(几乎不需要显式定义类型),完美支持 typescript。
- 可以在任意 页面/组件 里面 获取/修改任意 页面 的值。
- 支持所有的 redux 中间件,充分利用社区资源。
- api 继承
react-redux
,上手成本低。
文档
你可以点击这里获取 详细文档。
文件分为几个部分:
安装
npm install sim-react-redux --save
用法示例
1、定义每个页面各自的 state
const defaultState = {
title: '首页',
count1: 0,
count2: 0,
}
export default defaultState;
2、创建各个页面的 actorsFactory
import state from "./state";
import { createActorsFactory } from "sim-react-redux";
export default createActorsFactory(state, store => ({
async addCount1() {
const { count1 } = store.getState();
return {
count1: count1 + 1
};
},
async addCount2() {
const { count2 } = store.getState();
return {
count2: count2 + 1
};
}
}));
3、创建各个页面的 actorsFactory
合并,然后创建整个应用的 store
import { applyMiddleware } from 'redux';
import {
Provider,
createStore,
createActorsHook,
createSelectorHook,
combineActorsFactories
} from 'sim-react-redux';
import { createLogger } from 'redux-logger';
import homeActorsFactory from '../views/home/actors';
import userActorsFactory from '../views/user/actors';
const rootActorsFactory = combineActorsFactories({
home: homeActorsFactory,
user: userActorsFactory,
});
const useActors = createActorsHook(rootActorsFactory);
const useSelector = createSelectorHook(rootActorsFactory);
const logger = createLogger();
const store = createStore(rootActorsFactory, applyMiddleware(logger));
export {
store,
useActors,
useSelector,
Provider,
rootActorsFactory
}
4、把合并后的 actorsFactory
和 创建的 store
, 从顶层注入
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import { store, Provider, rootActorsFactory } from './store';
const App = () => (
<Provider actorsFactory={rootActorsFactory} store={store}>
<BrowserRouter>
{ }
</BrowserRouter>
</Provider>
)
render(<App />, document.getElementById('root'));
5、现在就可以在任意 页面/组件 中使用啦
import React, { FC } from 'react';
import { Button } from 'antd';
import { useActors, useSelector } from '../../../../store';
interface IProps { }
const Count01: FC<IProps> = () => {
const count1 = useSelector(({ home }) => home.count1);
const count2 = useSelector(({ home }) => home.count2);
const { home: { addCount1 } } = useActors();
return (
<div style={{ borderTop: '1px solid #ccc', padding: 10 }}>
<h4>count-01</h4>
<div>count-01: {count1}</div>
<div>count-01: {count2}</div>
<Button onClick={() => addCount1()}>count + 1</Button>
</div>
)
}
export default Count01
协议
sim-react-redux
遵循 MIT
协议。