Created
September 25, 2019 07:58
-
-
Save 101t/265e3f631d187dc19f0e190554d7c461 to your computer and use it in GitHub Desktop.
React + Redux state how it works?
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 from 'react'; | |
import { render } from 'react-dom'; | |
import { createStore } from 'redux'; | |
import { connect, Provider } from 'react-redux'; | |
const reducer = (state = {counter: 0}, action) => { | |
switch (action.type) { | |
case 'INCREMENT': | |
return {...state, counter: state.counter+1}; | |
case 'DECREMENT': | |
return {...state, counter: state.counter-1}; | |
default: | |
return state; | |
} | |
}; | |
const store = createStore(reducer, {counter: 0},window.devToolsExtension ? window.devToolsExtension() : undefined); | |
let Counter = ({counter, onIncrement, onDecrement}) => | |
(<div> | |
<div>{counter}</div> | |
<button onClick={onDecrement}>-</button> | |
<button onClick={onIncrement}>+</button> | |
</div>); | |
const mapStateToProps = (state) => { | |
return {counter: state.counter}; | |
} | |
const mapDispatchToProps = (dispatch) => { | |
return { | |
onIncrement: () => dispatch({type: 'INCREMENT'}), | |
onDecrement: () => dispatch({type: 'DECREMENT'}) | |
} | |
} | |
Counter = connect(mapStateToProps, mapDispatchToProps)(Counter); | |
render( | |
<Provider store={store}> | |
<Counter /> | |
</Provider> | |
, document.getElementById('root')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment