Redux --- 简单实现一个todoList (4) --- redux-thunk中间件

比如在Dispatch一个Action之后,到达reducer之前,进行一些额外的操作,就需要用到middleware(中间件)。 在实际工作中你可以使用中间件来进行日志记录、创建崩溃报告,调用异步接口或者路由

目的

有了react-thunk后,我们可以把 TodoList.js 中的 componentDidMount 业务逻辑放到这里来编写。也就是把向后台请求数据的代码放到actionCreators.js文件里。这样所有的业务逻辑都在redux中,方便集中管理。


1

安装

yarn add redux-thunk --save

引入,使用

import {createStore ,applyMiddleware} from 'redux';
import thunk from 'react-thunk';
const store = createStore(reducer,
	applyMiddleware(thunk)
);

为了能够用redux-dev-tool工具来调试我们的代码,代码需要做一些改动,添加一个增强件compose,以及几行固定代码,如下为index.js的完整代码

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

const composeEnhancers =   window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
    
const enhancer = composeEnhancers(applyMiddleware(thunk))
const store = createStore( reducer, enhancer) 
export default store   


2

react-thunk的好处在于,以前的action是一个对象,现在的action可以是一个函数了。

以前的action是一个对象

onDeleteItem = (selectId) => {
        const action = onDeleteItemAction(selectId);  //调用的是对象
        store.dispatch(action)
    }
export const onDeleteItemAction = (selectId) => ({  //对象:{type:'',value:''}
    type:DELETE_ITEM,
    value:selectId
})


现在的action可以是函数,函数同样写入actionCreator.js

componentDidMount(){
        const action = onGetInitList(); //这里的action为函数
        store.dispatch(action);
    }

把有关的业务逻辑放在onGetInitList 函数中,并且调用onGetInitListType 对象

export const onGetInitList = () =>{  
    return (dispatch) => {
        axios.get("https://5f48b1de57a10f001600ddf3.mockapi.io/api/todoList").then(res =>{
            console.log(res);
            const action = onGetInitListType(res.data);  //这里的action为对象
            dispatch(action);
        })
    }
}

export const onGetInitListType = (data) => ({
    type:GET_INITLIST,
    data
})

藏之介白石❀


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值