npx create-react-app redux-counter
cd redux-counter
npm install –save redux react-redux
Creamos Counter.js:
import React from 'react'; class Counter extends React.Component { state = { count: 0 } increment = () => { this.setState({ count: this.state.count + 1 }); } decrement = () => { this.setState({ count: this.state.count - 1 }); } render() { return ( <div> <h2>Counter</h2> <div> <button onClick={this.decrement}>-</button> <span>{this.state.count}</span> <button onClick={this.increment}>+</button> </div> </div> ) } } export default Counter;
Después de modificarlo:
import React from 'react'; import { connect } from 'react-redux'; function mapStateToProps(state) { return { count: state.count }; } class Counter extends React.Component { //state = { count: 0 } increment = () => { this.props.dispatch({ type: "INCREMENT" }); } decrement = () => { this.props.dispatch({ type: "DECREMENT" }); } render() { return ( <div> <h2>Counter</h2> <div> <button onClick={this.decrement}>-</button> <span>{this.props.count}</span> <button onClick={this.increment}>+</button> </div> </div> ) } } export default connect(mapStateToProps)(Counter);
App
import React from 'react'; import logo from './logo.svg'; import './App.css'; import Counter from './Counter'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; const initialState = { count: 0 }; function reducer(state = initialState, action) { console.log('reducer', state, action); switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; case 'DECREMENT': return { count: state.count - 1 }; case 'RESET': return { count: 0 }; default: return state; } } const store = createStore(reducer); function App() { return ( <Provider store={store}> <Counter /> </Provider> ); } export default App;