Created
August 22, 2018 14:41
-
-
Save deadkff01/2c6d18d3fee3dd08166847095164be1a to your computer and use it in GitHub Desktop.
React - Simple count with Redux
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 { render } from 'react-dom'; | |
import { createStore, combineReducers } from 'redux'; | |
import { connect, Provider } from 'react-redux'; | |
const countReducer = (state = { count: 0 }, action) => { | |
switch (action.type) { | |
case 'INC': return { count: state.count + 1 }; | |
case 'DEC': return { count: state.count - 1 }; | |
default: return state; | |
} | |
} | |
const reducers = combineReducers({ | |
counter: countReducer | |
}) | |
const actions = { | |
inc: () => ({ type: 'INC' }), | |
dec: () => ({ type: 'DEC' }), | |
}; | |
const store = createStore(reducers); | |
class App extends Component { | |
render() { | |
const { inc, dec, count } = this.props; | |
return ( | |
<div> | |
<button onClick={inc}>Increment</button> | |
<button onClick={dec}>Decrement</button> | |
<div>Value: {count}</div> | |
</div> | |
); | |
} | |
} | |
const mapStateToProps = ({ counter }) => { | |
return { count: counter.count }; | |
} | |
const AppContainer = connect(mapStateToProps, actions)(App); | |
render( | |
<Provider store={store}> | |
<AppContainer /> | |
</Provider>, | |
document.getElementById('root') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment