regular-redux-undo
v0.0.2
Published
the plugin of regular-redux to archieve undo and redo
Downloads
3
Readme
Regular Redux Undo
一个微型插件用于 Regular 组件实现Redux的undo、redo。配合rgl-redux
npm install regular-redux-undo rgl-redux
运行要求
- regularjs 0.6.0-beta.1以上版本
- babel 用于构建基于ES6语法的应用
用法
module/store.js
:
export default new Rex.Store({
state: {
count: 0
},
reducers: {
count(state, payload) {
let count = state.count;
count++;
return Object.assign({}, state, {count});
}
}
});
module/App.js
:
import store from './module/store';
import 'rgl-redux';
import './module/App';
const AppContainer = Regular.extend({
template: `
<StoreProvider store={store}>
<App />
</StoreProvider>
`,
config(data) {
data.store = store;
},
});
components/App.js
:
import { connect } from 'rgl-redux';
const App = Regular.extend({
name: 'App',
template: '<div>{count}</div><button on-click={this.onClick()}>click me to count!</button>',
onClick() {
this.$dispatch(changeFoo('bar'));
}
});
export default connect({
mapState(state) {
return {
count: state.count
};
},
dispatch: true,
})(App);
示例项目
示例项目位于 example
目录,进入example目录后,运行 npm run start && npm run watch
文档
注意
由于rgl-redux在组件初始化的时候并不会调用mapState,所以需要在组件实例化后this.$dispatch('@init/state')
Rex.Store
store的构造函数,接受一个配置对象config,用于创建app的store。
new Rex.Store({
state: {
count: 0
},
reducers: {
count(state, payload) {
let count = state.count;
count++;
return Object.assign({}, state, {count});
}
}
});
config.undoable
是否可以undo、redo,默认开启。
config.state
store的默认state,这个state是全局的(和模块区分,模块见下面文档)。
config.reducers
store全局reducer(和模块区分,模块见下面文档)。
config.modules
new Rex.Store({
...
state: {
count: 0
},
modules: {
moduleA: {
state: {
count: 1
},
reducers: {
moduleAcount(moduleA, payload) {
let count = moduleA.count;
count++;
return Object.assign({}, moduleA, {count});
}
}
}
}
....
});
//全局state会和局部state进行合并,实例中会合成为:
//state: {
// count: 0,
// moduleA: {
// count: 1
// }
//}
//模块中的reducer注入的state会自动换成module层次的state
注意:如果有模块的时候,全局的state必须是一个对象
config.middlewares
中间件,可用于数据修改无关的操作,例如发送保存请求,记录日志等。
function myMiddleware(context, next) {
//context的方法: dispatch, undo, redo, subscribe, getState
//next:只有执行了next()后dispatch才会往下执行
}
new Rex.Store({
...
middlewares:[myMiddleware]
....
});
config.modifiers
可用于对reducer返回的state做一些改变,业务中经常用于数据关联处理。
function myModifiers(reducer) {
return (state, action) {
//do something
let newState = reducer(state, action);
//do something
return newState; //这里要return新的state
}
}
new Rex.Store({
...
modifiers:[myModifiers]
....
});
内置dispatch的方法
//回退历史
this.$dispatch("undo") //store.dispatch("undo")
//前进
this.$dispatch("redo") //store.dispatch("redo")
//重置state
this.$dispatch("@init/state") //store.dispatch("@init/state")
//替换state
this.$dispatch("@replace/state") //store.dispatch("@replace/state")
License
MIT