Created
February 7, 2018 16:22
-
-
Save VingeB0/65f807d63f103447001fa10deddd72a1 to your computer and use it in GitHub Desktop.
react flux - simple example counter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {Component} from 'react'; | |
import logo from './logo.svg'; | |
import './App.css'; | |
import {EventEmitter} from 'events'; | |
import {Dispatcher} from 'flux'; | |
const AppDispatcher = new Dispatcher(); | |
const CHANGE_EVENT = 'CHANGE'; | |
let _count = 0; //private | |
const CounterStore = Object.assign({}, EventEmitter.prototype, { | |
emitChange() { | |
console.log(_count); | |
this.emit(CHANGE_EVENT); | |
}, | |
addChangeListener(callback) { | |
this.on(CHANGE_EVENT, callback); | |
}, | |
removeChangeListener(callback) { | |
this.removeListener(CHANGE_EVENT, callback); | |
}, | |
getCount() { | |
return _count; | |
} | |
}); | |
AppDispatcher.register(action => { | |
if (action.type === 'INCREMENT') { | |
_count++; | |
CounterStore.emitChange(); | |
} | |
if (action.type === 'DECREMENT') { | |
_count--; | |
CounterStore.emitChange(); | |
} | |
}); | |
function increment() { | |
AppDispatcher.dispatch({ | |
type: 'INCREMENT' | |
}) | |
} | |
function decrement() { | |
AppDispatcher.dispatch({ | |
type: 'DECREMENT' | |
}) | |
} | |
class App extends Component { | |
constructor() { | |
super(); | |
this.state = this.getStateFromFLux(); | |
this.updateState = this.updateState.bind(this); | |
} | |
getStateFromFLux() { | |
return { | |
count: CounterStore.getCount() | |
} | |
} | |
updateState() { | |
this.setState(this.getStateFromFLux()); | |
} | |
componentDidMount() { | |
CounterStore.addChangeListener(this.updateState); | |
} | |
componentWillUnmount() { | |
CounterStore.removeChangeListener(this.updateState); | |
} | |
render() { | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
<img src={logo} className="App-logo" alt="logo"/> | |
<h1 className="App-title">Welcome to React</h1> | |
</header> | |
<div className="App"> | |
<h1>React Flux Counter</h1> | |
<div> | |
<button onClick={decrement}>-</button> | |
{this.state.count} | |
<button onClick={increment}>+</button> | |
</div> | |
</div> | |
{/*<CounterFlux/>*/} | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment