前言:

  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. 枪弹辩驳(弹丸论破)即将登陆PC

    Spike Chunsoft在PSP上的经典推理游戏: 枪弹辩驳1(Danganronpa: Trigger Happy Havoc)即将登陆PC, PC党有福了. 不过我在PSVita上已经玩完了两 ...

  2. Yii2 设计模式——设计模式简介

    我们首先来思考一个问题:作为工程师,我们的价值是什么? 笔者认为是——解决用户问题. 我们的任何知识和技能,如果不能解决特定的问题,那么就是无用的屠龙之术:我们的任何经验,如果不能对解决新的问题有用, ...

  3. 20175202 《Java程序设计》第九周学习总结

    20175202 2018-2019-2 <Java程序设计>第九周学习总结 教材知识点总结 第11章 JDBC与MySQL数据库 MySQL数据库管理系统 MySQL数据库管理系统,简称 ...

  4. SQL 快速生成不重复的卡号

    --0042-9923-3598 select id = right('000000000000' + cast(cast(rand(checksum(newid()))*1000000000000 ...

  5. pagination.js 使用

    pagination.js 使用方式 $('.paginationjs').pagination({ dataSource: 'DetailImage?handler=Search', locator ...

  6. 【Leecode】两数之和

    学习使用标准模板库(STL)中的map,hash_map.涉及数据结构知识:哈希表,红黑树. map的使用方法 https://www.cnblogs.com/fnlingnzb-learner/p/ ...

  7. lnmp一件安装包 搭建laravel 环境(lnmp1.4)(报错500)

    https://blog.csdn.net/huangyuxin_/article/details/78998486

  8. 错误界面 SQL2008备份集中的数据库备份与现有的数据库不同,错误号码:3154。

    转载来源  https://blog.csdn.net/zaocha321/article/details/8466735 因为我也用这个方法成功了.所以记录下来 错误界面 SQL2005备份集中的数 ...

  9. excel表格公式无效、不生效的解决方案及常见问题、常用函数

    1.表格公式无效.不生效 使用公式时碰到了一个问题,那就是公式明明已经编辑好了,但是在单元格里不生效,直接把公式显示出来了,网上资料说有4种原因,但是我4种都不是,是第5种原因,如下图: 这种情况是由 ...

  10. yum搭建 Lamp环境

    yum搭建Lamp yum install -y httpd yum install -y nano rpm 安装 Php7 相应的 yum源 rpm -Uvh https://dl.fedorapr ...