Implementation effect

Entry file index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import store from './redux/store'

ReactDOM.render(<App store={store}/>.document.querySelector('#root'))

store.subscribe(() = > {
    ReactDOM.render(<App store={store}/>.document.querySelector('#root'))});Copy the code

Shell file app.js

import React, { Component } from 'react';

class App extends Component {

    componentDidMount() {
        console.log(this.props.store);
    }
    Increment = () = > {
        const {value} = this.selectNumber;
        this.props.store.dispatch({type: 'increment'.data: value*1})}; Decrement =() = > {
        const {value} = this.selectNumber;
        this.props.store.dispatch({type: 'decrement'.data: value*1})
    }
    IncrementIfOdd = () = > {
        const {value} = this.selectNumber;
        const count = this.props.store.getState();
        if (count % 2! = =0) {
            this.props.store.dispatch({type: 'increment'.data: value*1});
        }
    }
    IncrementAsync = () = > {
        const {value} = this.selectNumber;
        setTimeout(() = > {
            this.props.store.dispatch({type: 'increment'.data: value*1});
        },1000)}render() {
        const count = this.props.store.getState();
        return (
            <div>
                <h1>The current sum is: {count}</h1>
                <select ref={c= > this.selectNumber = c}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>&nbsp;&nbsp;
                <button onClick={this.Increment}>+</button>&nbsp;
                <button onClick={this.Decrement}>-</button>&nbsp;
                <button onClick={this.IncrementIfOdd}>Odd number is +</button>&nbsp;
                <button onClick={this.IncrementAsync}>Asynchronous +</button>
            </div>); }}export default App;
Copy the code

reducer.js

let initState = 0;
export default function operatorCount(preState = initState, action) {
    // Rule: You cannot modify the passed preState
    console.log('Reducer was called');
    const { type, data } = action;
    let newState;
    switch (type) {
        case 'increment':
            newState = preState + data;
            return newState;
        case 'decrement':
            newState = preState - data;
            return newState;
        default:
            returnpreState; }}Copy the code

store.js

import {createStore} from 'redux';
import reducer from './reducer'
export default(createStore(reducer))
Copy the code