Created
October 6, 2020 14:34
-
-
Save bablukpik/366a09c2f10a56a2af66f278f2faafd1 to your computer and use it in GitHub Desktop.
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
************Source Code************** | |
// src/actions/incrementAction.js | |
const incrementAction = { | |
type: 'increment', | |
payload: 1 | |
} | |
export default incrementAction; | |
// src/actions/decrementAction.js | |
const decrementAction = { | |
type: 'decrement', | |
payload: 1 | |
} | |
export default decrementAction; | |
// src/reducers/counterReducer.js | |
const defaultState = { | |
counting: 1 | |
} | |
const counterReducer = (state = defaultState, action) => { | |
switch (action.type) { | |
case 'increment': | |
return { | |
counting: state.counting + action.payload | |
} | |
case 'decrement': | |
return { | |
counting: state.counting - action.payload | |
} | |
default: | |
return state; | |
} | |
} | |
export default counterReducer; | |
// src/store.js | |
import { createStore } from 'redux'; | |
import counterReducer from './reducers/counterReducer'; | |
const store = createStore(counterReducer); | |
export default store; | |
// src/components/Couter.js | |
import React, { Component } from 'react'; | |
import { connect } from 'react-redux'; | |
import incrementAction from '../actions/incrementAction'; | |
import decrementAction from '../actions/decrementAction'; | |
class Counter extends Component { | |
render() { | |
console.log(this.props); | |
return <div> | |
<p>{ this.props.counting }</p> | |
<button onClick={ this.props.increment }>Increment</button> | |
<button onClick={ this.props.decrement }>Decrement</button> | |
</div> | |
} | |
} | |
// Getter | |
const mapStateToProps = (state) => ({ ...state }); | |
// Setter | |
const mapDispatchToProps = (dispatch) => ({ | |
increment: () => dispatch(incrementAction), | |
decrement: () => dispatch(decrementAction) | |
}); | |
export default connect(mapStateToProps, mapDispatchToProps)(Counter); | |
// src/index.js | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import * as serviceWorker from './serviceWorker'; | |
import { Provider } from 'react-redux'; | |
import store from './store'; | |
import Counter from './components/Counter' | |
ReactDOM.render( | |
<React.StrictMode> | |
<Provider store={store}> | |
<Counter /> | |
</Provider> | |
</React.StrictMode>, | |
document.getElementById('root') | |
); | |
serviceWorker.unregister(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment