前言:

  redux默认不支持异步编程,需要下载redux插件(异步中间件)

  如何下载:

    npm install --save redux-thunk

项目结构:

代码:

import React, {Component} from 'react'
import PropTypes from 'prop-types'

export default class Counter extends Component {
    static propTypes = {
        count: PropTypes.number.isRequired,
        increment: PropTypes.func.isRequired,
        decrement: PropTypes.func.isRequired,
        incrementAsync: PropTypes.func.isRequired
    }

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

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

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

    incrementAsync = () => {
        //1.得到选择的增加数量
        const number = this.select.value * 1

        this.props.incrementAsync(number)
    };

    render() {
        const {count} = this.props
        // 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>
        )
    }
}

counter.jsx

import React from 'react'
import {connect} from "react-redux";

import {decrement, increment, incrementAsync} from "../redux/actions";
import Counter from '../components/counter'

export default connect(
    state => ({count: state}),
    {increment, decrement, incrementAsync}
)(Counter)

app.jsx

/*
* 包含所有action type的常量字符串
* */

export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';

action-types.js

import {INCREMENT, DECREMENT} from '../redux/action-types';
/*
* 包含所有action creator
* 同步的action都是返回一个对象
* 异步的action返回的是一个函数
* */

//增加
export const increment = (number) => ({
    type: INCREMENT, data: number
})
//减少
export const decrement = (number) => ({
    type: DECREMENT, data: number
})
//异步action
export const incrementAsync = (number) => {
    return dispatch => {
        //异步的代码
        setTimeout(() => {
            //1S之后才去分发一个增加的action
            dispatch(increment(number))
        }, 1000)
    }
}

actions.js

/*
* 包含n个reducer函数的模块
* */
export function counter(state = 0, action) {

    console.log('counter()', state, action)

    switch (action.type) {
        case 'INCREMENT':
            return state + action.data
        case 'DECREMENT':
            return state - action.data
        default:
            return state
    }

}

reducers.jsx

import {createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk'

import {counter} from './reducers';

//生成store对象
const store = createStore(
    counter,
    applyMiddleware(thunk)//应用上异步中间件
);//内部会第一次调用reduer函数得到初始state
console.log(store, store.getState());

export default store

store.js

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux'

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

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

index.js

42_redux_counter应用_redux异步版本的更多相关文章

  1. struts 多文件上传 annotation注解(零配置)+ ajaxfileupload + 异步 版本

    [本文简介] struts 多文件上传.基于”零配置“+"ajaxfileupload" 的一个简单例子. [导入依赖jar包] jquery-1.7.2.js : http:// ...

  2. 40_redux_counter应用_redux完善版本

    项目结构: 代码: import React from 'react'; import ReactDOM from 'react-dom'; import store from './redux/st ...

  3. java8的版本对组合式异步编程

    讨论了Java 8中的函数式数据处理,它可以将对集合数据的多个操作以流水线的方式组合在一起.本节继续讨论Java 8的新功能,主要是一个新的类CompletableFuture,它是对65节到83节介 ...

  4. [.NET] 怎样使用 async & await 一步步将同步代码转换为异步编程

    怎样使用 async & await 一步步将同步代码转换为异步编程 [博主]反骨仔 [出处]http://www.cnblogs.com/liqingwen/p/6079707.html  ...

  5. [Android]异步 layout inflation(翻译)

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5829809.html 异步 layout inflation ...

  6. Code First系列之视图,存储过程和异步API

    返回<8天掌握EF的Code First开发>总目录 本篇目录 视图View 存储过程 使用存储过程CRUD 异步API 本章小结 自我测试 本系列的源码本人已托管于coding上:点击查 ...

  7. 异步编程系列第04章 编写Async方法

    p { display: block; margin: 3px 0 0 0; } --> 写在前面 在学异步,有位园友推荐了<async in C#5.0>,没找到中文版,恰巧也想提 ...

  8. 异步编程系列06章 以Task为基础的异步模式(TAP)

    p { display: block; margin: 3px 0 0 0; } --> 写在前面 在学异步,有位园友推荐了<async in C#5.0>,没找到中文版,恰巧也想提 ...

  9. Python-09-线程、进程、协程、异步IO

    0. 什么是线程(thread)? 线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元.一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆 ...

随机推荐

  1. git编译安装

    因yum安装的git版本过低,所以尝试使用编译安装git 以下为编译安装时执行的命令 tar xf git-2.9.5.tar.gz cd git-2.9.5yum install curl-deve ...

  2. 集成direnv 与docker-compose 进行环境变量管理

    direnv 是一个不错的换将变量管理工具,同时日常的开发测试中我们使用docker-compose 会比较多,一般我们的玩法是 可以再docker-compose 中指定环境变量,可以通过envir ...

  3. Day 18 常用模块(二)

    一.随机数:RANDOM 1.(0,1)小数:random.random() 2.[1,10]整数:random.randint(1,10) 3.[1,10)整数:random.randrang(1, ...

  4. [JAVA]字节数组流

    import java.io.*; public class ByteArrayStream { public static void main(String[] args) { byte[] dat ...

  5. markdown特殊符号语法

    符号 说明           对应编码 &    AND符号        & < 小于           < > 大于           > _    ...

  6. 1080P60视频源---verilog

    1080P60视频源---verilog `timescale 1ns / 1ps ////////////////////////////////////////////////////////// ...

  7. RK3399/NanoPC-T4开发板使用/sys/class/gpio操作外接GPIO设备-【申嵌视频-RK3399篇】

    实验2:RK3399/NanoPC-T4开发板使用/sys/class/gpio操作外接GPIO设备,比如外接一个LED模块,通过GPIO1_A0管脚 1 介绍   LED模块   Matrix-LE ...

  8. Excel技巧--提取中文字串

    类似的,如果要提取上图第1列的商品,不要型号,如第2列. 可以考虑使用SEARCHB函数. searchb与search的区别,在于searchb函数以字节为单位搜索,search函数以字符为单位搜索 ...

  9. element-ui 点击获取table的行索引

    <el-table :data="list" v-loading.body="listLoading" element-loading-text=&quo ...

  10. 接口自动化 基于python+Testlink+Jenkins实现的接口自动化测试框架

    链接:http://blog.sina.com.cn/s/blog_13cc013b50102w94u.html