My React + Redux counter
by Allie Yu
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>
<div id="root"></div>
JavaScript
const Initial_state = {count:0}
const counter = (state=Initial_state, action) => {
switch(action.type){
case 'INCREMENT':
return {count : state.count + 1}
case 'DECREMENT':
return {count : state.count - 1}
default:
return state;
}
}
const store = Redux.createStore(counter);
class Counter extends React.Component{
constructor(props){
super(props);
console.log(this.props);
}
IncreaseHandler = () => {
store.dispatch({ type: 'INCREMENT' });
}
DecreaseHandler = () => {
store.dispatch({ type: 'DECREMENT' });
}
render(){
return(
<div>
<span>React Redux</span>
<h2>{this.props.count}</h2>
<button onClick = {this.IncreaseHandler}>+</button>
<button onClick = {this.DecreaseHandler}>-</button>
</div>
)
}
}
const { Provider, connect } = ReactRedux;
const mapStateToProps = state => {
return state;
}
const mapDispatchToProps = dispatch =>{
return{
Increase: ()=>{
return dispatch({type: "INCREMENT"})},
Decrease: ()=>{
return dispatch({type: "DECREMENT"})}
}
}
/* const mapDispatchToProps = dispatch => {
return {
Increase : () => {
return dispatch({type:'INCREMENT'})
}
Decrease : () => {
return dispatch({type: 'DECREMENT'})
}
}
} */
const App = connect(mapStateToProps, mapDispatchToProps)(Counter);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
)