[React] 基于ES6 Class的React Store.
现金的SPA大部分使用Flux
和Redux
, 但是这两个库对于异步的处理却并不是十分友善, 且复杂的代码使得结构难以理解.
Classux
是基于ES6 Class, 和使用decorator
特性的一个React Store库.
首先 npm i classux
安装库,
由于需要使用babel转译, 此例使用了webpack来进行编译.
关键配置如下:
'use strict';
const path = require('path');
const webpack = require('webpack');
module.exports = {
......
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
plugins: [
'transform-decorators-legacy',
'transform-async-to-generator',
],
presets: ['es2015'],
}
}
]
},
......
};
loggingMiddleware.js
export default async function loggingMiddleware(next, state, action, ...params) {
console.info(`[STATE]`, state);
console.info(`[ACTION] ${action} `, ...params);
const s = await next();
console.info(`[AFTER-STATE]`, s);
return s;
}
CounterStore.js
import Store, {
Reducer,
Inject,
} from 'classux';
import loggingMiddleware from 'middlewares/loggingMiddleware';
@Inject(loggingMiddleware)
class CounterStore extends Store {
constructor() {
super({
count: 0,
});
}
@Reducer('increase')
async increase() {
await new Promise(resolve => setTimeout(resolve, 1000));
const state = this.getState();
state.count ++;
return state;
}
}
export default new CounterStore();
App.js
import React from 'react';
import CounterStore from 'stores/CounterStore';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
@CounterStore.onUpdate()
onCounterStoreUpdate(state) {
this.setState({
count: state.count,
});
}
render() {
return <div>
<h1>{this.state.count}</h1>
<button
onClick={e => CounterStore.dispatch('increase')}>
increase
</button>
</div>
}
}
这样, 一个简单的使用了classux
的store就可以用啦.
更多详情请前往 https://github.com/joesonw/classux 了解哦.
1 回复
mark From Noder