Created
July 5, 2020 05:05
-
-
Save SimonAKing/36a0595dc4334d8a93d9667552fa0e12 to your computer and use it in GitHub Desktop.
Redux-Counter
This file contains 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 PropTypes from 'prop-types' | |
import ReactDOM from 'react-dom' | |
import { createStore } from 'redux' | |
import { Provider, connect } from 'react-redux' | |
// React component | |
class Counter extends Component { | |
render() { | |
const { value, onIncreaseClick } = this.props | |
return ( | |
<div> | |
<span>{value}</span> | |
<button onClick={onIncreaseClick}>Increase</button> | |
</div> | |
) | |
} | |
} | |
Counter.propTypes = { | |
value: PropTypes.number.isRequired, | |
onIncreaseClick: PropTypes.func.isRequired | |
} | |
// Action | |
const increaseAction = { type: 'increase' } | |
// Reducer | |
function counter(state = { count: 0 }, action) { | |
const count = state.count | |
switch (action.type) { | |
case 'increase': | |
return { count: count + 1 } | |
default: | |
return state | |
} | |
} | |
// Store | |
const store = createStore(counter) | |
// Map Redux state to component props | |
function mapStateToProps(state) { | |
return { | |
value: state.count | |
} | |
} | |
// Map Redux actions to component props | |
function mapDispatchToProps(dispatch) { | |
return { | |
onIncreaseClick: () => dispatch(increaseAction) | |
} | |
} | |
// Connected Component | |
const App = connect( | |
mapStateToProps, | |
mapDispatchToProps | |
)(Counter) | |
ReactDOM.render( | |
<Provider store={store}> | |
<App /> | |
</Provider>, | |
document.getElementById('root') | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment