redux基本流程和redux-thunk 中间件

问题?什么是中间件,是谁和谁之间的中间件呢?

 

说这个问题之前,先搞清楚redux的流程(顺序如下参考上图):

           Components:派发一个action,action通过store的dispatch方法派发给store

           store:store接收到action连同之前的state一起传给reducer

           reducer:reducer返回一个新的数据给store

           store:store再去改变自己的state

这就是redux的标准流程

 

那么redux中间件的流程指的是谁和谁之间呢?

redux中间件的中间指的就是action和store之间

之前我们都知道在redux中,action只能是一个对象,直接把这个对象派发给了store,现在当我们使用redux-thunk之后,action可以是函数了,

为什么是函数了呢?

    action通过dispatch方法传递给store、那么action和store之间是不是就是dispatch这个方法?所以我们说的中间件实际上就是对dispatch这个方法的封装(升级),最原始的dispatch方法接收到一个对象之后,会把这个对象传递给store(这是没有中间件的情况)。当我们对dispatch方法做了一个升级之后,比如使用了redux-thunk这个中间件,这个时候,当你通过dispatch方法传递给store是一个函数的时候,这个时候store已经升级了,它就不会只接把这个函数传递给store,它会让你这个函数先执行、执行完之后,需要调用store的时候再去调用、如果你传递的是个对象,那么它会和最原始的时候一样,直接把对象传递给store

 

一句话:redux-thunk就是对dispatch做了一个升级,之前dispatch只能派发对象,升级之后传递对象和函数都可以,

 

actionTypes.js  原始的action写法如下:

export const del_list_item = 'del_list_item';

export const delectToDoList = (index) => {
    return {
        type: del_list_item,
        index
    }
}

actionTypes.js  使用redux-thun之后:

export const initListAxtion = (data) => {
    return {
        type: init_list,
        data
    }
}


export const getTodoList = () => {
    return (dispatch) => {
        axios.get('http://172.16.1.159:8090/classes/class/getClass/v1.0').then((res) => {
            console.log(res.data.data.datalist);
            const action = initListAxtion(res.data.data.datalist)
            dispatch(action)
        })
    }
}

组件里:

import { getTodoList} from './store/actionTypes'

componentDidMount() {
        store.dispatch(getTodoList())
    }

除了redux-thunk可以做异步数据请外之后,还有一个rudux-saga,下篇再说

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值