redux-thunk

中间件原理
中间件?是谁的中间件?谁和谁的中间?
是action和store中间,action和store中间是通过dispatch方法连接的,所以,redux-thunk中间件,实际上是对dispatch方法做的封装改造!!!

redux-logger
redux-thunk 异步逻辑放到action中处理
redux-saga 异步逻辑单独处理

1.redux-thunk是redux的中间件,是用来丰富redux的功能的,不是react的中间件
好处:
正常情况下,redux中的actionCreators创建的action值能是对象,但是,使用了redux-thunk后,action的返回值可以函数!!!可以写异步代码

  • 下载插件 npm install redux-thunk
  • 使用:创建store时使用
import {createStore,applyMiddleware,compose} from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';
// 1.先引入applyMiddleware
// 2. 通过redux创建store时使用中间件,中间件是redux的,不是react的
// 同时使用redux-thunk和__REDUX_DEVTOOLS_EXTENSION_COMPOSE__这两个中间件
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
const enhancer = composeEnhancers(applyMiddleware(thunk));
const store = createStore(
  reducer, // 构建初始数据
   // chrome调试redux
   enhancer
  
);

这样编写的action可以长这样:

// 使用redux-thunk后 ,action返回的东西可以是函数
export const getTodoList = ()=>{
  return (dispatch)=>{
       axios.get('/list.json').then((res)=>{
        const data =res.data;
        dispatch('xx-action');
    }).catch()
  }
}

当store.dispatch(action),若action是一个function,store会自动调用这个方法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值