redux-thunk中间件的使用

一、作用

        redux-thunk 可以处理 函数形式 的action.从而就可以在函数形式的action中执行异步操作代码.

使用前:

actions/

const action1 = {type: 'todos/add', payload: '学习redux'}

// 组件使用
dispatch(action1)

使用后:

actions/

const action1 = async (dispatch) =>{
  const res = await 异步动作()
  dispatch({type: 'todos/add', payload: '学习redux'})
}

//组件使用
dispatch(action1)

二、步骤

1.安装:npm i redux-thunk

2.使用:store/index.js

        1)导入 redux-thunk , applyMiddleware

import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'

        2)调用applyMiddleware将 thunk 添加到中间件列表中

const store = createStore(rootReducer, applyMiddleware(thunk))

        3)修改 action creator,返回一个函数,其形参就是redux的dispatch

./src/store/actions/

const addTodo = (name)=> {
  return async (dispatch) =>{
    const res = await 异步动作()
    dispatch({type: 'todos/add', payload: name})
  }
}

//组件使用action不要忘记导入
dispatch(addTodo('学习redux'))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值