40_redux_counter应用_redux完善版本

时间:2020-12-02 16:52:17

项目结构:

40_redux_counter应用_redux完善版本

代码:

import React from 'react';
import ReactDOM from 'react-dom';

import store from './redux/store'
import App from './components/app';

function render() {
    ReactDOM.render(<App store={store}/>, document.getElementById('root'));
}

//初始化渲染
render()

//订阅监听(store中的状态变化了,就会自动调用重绘)
store.subscribe(render)

index.js

import React, {Component} from 'react'

import * as actions from '../redux/actions'

export default class App extends Component {

    increment = () => {
        //1.得到选择的增加数量
        const number = this.select.value * 1
        //2.调用store的方法更新状态
        this.props.store.dispatch(actions.increment(number))

    };

    decrement = () => {
        //1.得到选择的增加数量
        const number = this.select.value * 1
        //2.调用store的方法更新状态
        this.props.store.dispatch(actions.decrement(number))
    };

    incrementIfOdd = () => {
        //1.得到选择的增加数量
        const number = this.select.value * 1
        //2.得到原本的count状态
        const count = this.props.store.getState()
        //3.判断,满足条件再更新状态
        if (count % 2 === 1) {
            //调用store方法更新状态
            this.props.store.dispatch(actions.increment(number))

        }
    }

    incrementAsync = () => {
        //1.得到选择的增加数量
        const number = this.select.value * 1
        //启动延时定时器
        setTimeout(() => {
            this.props.store.dispatch(actions.decrement(number))
        }, 1000)
    };

    render() {
        const count = this.props.store.getState()
        // debugger
        return (
            <div>
                <p>click {count} times</p>
                <div>
                    <select ref={select => this.select = select}>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                    </select>&nbsp;
                    <button onClick={this.increment}>+</button>
                    &nbsp;
                    <button onClick={this.decrement}>-</button>
                    &nbsp;
                    <button onClick={this.incrementIfOdd}>increment odd</button>
                    &nbsp;
                    <button onClick={this.incrementAsync}>increment async</button>
                    &nbsp;
                </div>
            </div>
        )
    }
}

app.jsx

import {createStore} from 'redux';
import {counter} from './reducers';

//生成store对象
const store = createStore(counter);//内部会第一次调用reduer函数得到初始state
console.log(store, store.getState());

export default store

store.js

import {INCREMENT, DECREMENT} from '../redux/action-types';
/*
* 包含所有action creator
* */

//增加
export const increment = (number) => ({
    type: INCREMENT, data: number
})
//减少
export const decrement = (number) => ({
    type: DECREMENT, data: number
})

actions.js