$ yarn add flux
// store/index.js
const EventEmitter = require( 'events' ).EventEmitter
const store = {
...EventEmitter.prototype,
state: {
count: 0
},
getState () {
return this.state
}
}
export default store
import store from './store'
class xxx extends React.Component{
constructor () {
super()
this.state = {
count: store.getState().count
}
}
render () {
return (
<div>
<p> { this.state.count } </p>
</div>
)
}
}
用户操作,用户点击按钮,执行当前组件中的方法,这个方法的逻辑实际上是actionCreators中的方法
创建actionCreators.js
import * as type from './type'
import dispatcher from './dispatcher';
const actionCreators = {
increment () {
// 创建动作
let actions = {
type: type.INCRMENT
}
// dispatcher来通过dispatch 发送actions
dispatcher.dispatch( actions )
}
}
export default actionCreators
创建dispatcher.js
import { Dispatcher } from 'flux';
import * as type from './type'
import state from './state'
const dispatcher = new Dispatcher()
// dispatcher.register( callback )
dispatcher.register( ( actions) => {
switch ( actions.type ) {
case type.INCRMENT:
// 用户操作了
state.count++
break;
default:
break;
}
})
export default dispatcher
通过store的事件的发布和订阅进行 当前组件中 state 的重新赋值
import React from 'react';
import logo from './logo.svg';
import './App.css';
import store from './store'
import actionCreators from './store/actionCreators';
class App extends React.Component {
constructor () {
super()
this.state = {
count: store.getState().count
}
}
increment () {
actionCreators.increment()
store.emit('count')
}
componentDidMount () {
store.on('count', () => {
this.setState({
count: store.getState().count
})
})
}
render () {
return (
<div>
<h3> flux </h3>
<button onClick = { this.increment }> + </button>
<p> count: { this.state.count } </p>
</div>
)
}
}
export default App;