【React】知识点归纳:redux 异步编程

一、下载 redux 插件(异步中间件)

npm install --save redux-thunk

二、案例

效果:

【React】知识点归纳:redux 异步编程

源代码:

对比 使用react-redux编写此案例
网址:https://blog.csdn.net/qq_41846861/article/details/86702584

  1. index.js
    引入redux-thunk插件
    applyMiddleware(thunk)
import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
// 根据 counter 函数创建 store 对象
const store = createStore(
	counter,
	applyMiddleware(thunk) // 应用上异步中间件
)
  1. redux/actions.js
    异步action返回一个函数
/*
包含所有的action creator
同步action返回一个对象
异步action返回一个函数
*/
//增加

import {INCREMENT,DECREMENT} from '../redux/action-types'

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

//异步action
export const incrementAsync = (number) => {
    return dispatch => {
        //在函数中写异步代码
        setTimeout(() =>{
            //一秒之后才去分发一个增加的action
            dispatch(increment(number))
        },1000)
    }
}
  1. components/counter.jsx
    不再使用setTimeout()延迟定时器,使用incrementAsync
incrementAsync  = () =>{
        //1.得到选择的更新数量
        const number = this.select.value*1

        this.props.incrementAsync(number)
      /*  //启动延迟定时器
        setTimeout(() =>{
            //3.更新状态
            // this.props.store.dispatch({type:INCREMENT,data:number})
            this.props.increment(number)
        },1000)*/
    }
  1. containers/app.jsx
    增加incrementAsync
import React from 'react'
import {connect} from 'react-redux'

import {increment,decrement,incrementAsync} from '../redux/actions'
import Counter from '../components/counter'
export default connect(
    state => ({count:state}),
    {increment,decrement,incrementAsync}
)(Counter)

注:只改写部分关于异步的代码,其他未变。