redux-thunk的简单使用

thunk

我们常常需要在redux中实现异步的数据获取等操作,这个时候就可以用到thunk

1、安装thunk

yarn add redux-thunk

2、创建store的时候引入中间件和配置

import {createStore,applyMiddleware} from 'redux'
import reducer from './reducer'
import thunk from 'redux-thunk'

let middleWares = applyMiddleware(thunk)
//通过middleWares将中间件传递给createStore

const store = createStore(reducer,middleWares)

3、使用thunk

我们原本的原本的actionCreators中只能返回的是个扁平的对象,这里我们是通过一个计数器来讲解,加法操作是使用thunk,而减法操作时通过了原始写法。

//actionCreators
import {INCREMENT,DECREMENT} from './actionType'
//从actionType中引入action的类型

const increment = (payload) =>{
    return{
        type:INCREMENT,
        payload
    }
}
//模拟异步写在这,action就可以是一个函数
const asyncincrement=()=>{
    return (dispath)=>{
        setTimeout(()=>{
            let payload = 8
            dispath(increment(payload))
        },2000)
    }
}

//使用thunk前是一个扁平的对象
const decrement = () =>{
    return{
        type:DECREMENT
    }
}

export {asyncincrement,decrement}

然后就可以在connect中这样写

import {connect} from 'react-redux'
import {asyncincrement,decrement} from './actionCreators'
//解构出方法

const mapState=(state)=>{
    return {
        count:state.count
    }
}

const mapDispatch=(dispatch)=>{
    return{
        asyncincrement:()=>{
            dispatch(asyncincrement())
            //派发操作
            console.log('connect +')
        },
        decrement:()=>{
            dispatch(decrement())
            console.log('connect -')
        }
    }
}
export default connect(mapState,mapDispatch)

然后需要使用该方法的地方可以这么写,

import React, { Component } from 'react'
import connect from './connect'
//引入connect

class Button extends Component {

    handleClick=()=>{
        if(this.props.children==='+'){
            this.props.asyncincrement()
            //通过this.props来引入方法并使用
        }else{
            this.props.decrement()
        }
    }

    render() {
        return (
            <button onClick={this.handleClick}>
                {this.props.children}
            </button>
        )
    }


}

export default connect(Button)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值