24.redux-thunk的使用

本文详细介绍了Redux-Thunk中间件的原理及应用,解析其如何使dispatch方法支持函数作为参数,从而实现异步操作。同时,文章还探讨了如何结合Redux-DevTools进行状态管理和调试,为开发者提供了实用的配置示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.github上搜索redux-thunk,他是redux的中间件,作用主要是让dispatch(action) 方法可以传入一个函数,而不一定是action对象

准确的来说是传入的函数的返回值 可以是一个方法或者函数 不一定是action对象 只是这个函数能够接收到dispatch 对象return的时候在执行一下 dispatch(aciton) 这个时候就可以是一个对象了

相当于在dispatch外面装饰了一个方法 这个方法处理了逻辑之后 在执行dispatch()

这个函数可以return 一个函数 该函数可以接收一个dispatch方法 然后可以实现请求后台数据之后调用dispatch方法改变store值

2.关于如何使用和配置可以参考GitHub上面的文档介绍 ,上面都是英文文档

注意点

renderItem={(item, index) => (<List.Item onClick={() => { props.deleteItem(index) }}

renderItem={(item, index) => (<List.Item onClick={(index) => { props.deleteItem(index) }} //onClick中的index参数不是外部函数的index参数而是事件的event对象,有e.target 可以打印一下

注意变量的作用域问题 外部的index参数 是作用于 整个方法,所以可以直接传入到onClick方法中

 

同时使用thunk 中间件 和redux-devtools-extensions 工具

import { createStore, applyMiddleware, compose } from 'redux';

import thunk from 'redux-thunk'

import reducer from '../reducer/';

//通过官方文档的使用方式

const composeEnhancers =

typeof window === 'object' &&

window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?

window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({

}) : compose;

 

const enhancer = composeEnhancers(

//applyMiddleware(...middleware),

applyMiddleware(thunk),

);

//通过applyMiddleware 使用redux 的中间件thunk

const store = createStore(reducer, enhancer);

// const store = createStore(reducer, applyMiddleware(thunk));

export default store

 

actionCreator //把请求抽出来放到action 中 逻辑清洗 便于自动化测试

export const getToDoList = () => {

return (dispatch) => {

axios.get('/apis/getMv').then((res) => {

console.log('res', res)

dispatch(initItem(res.data));

}).catch(() => {

})

}

}

//如果使用调用方法

componentDidMount = () => {

// axios.get('/apis/getMv').then((res) => {

// console.log('res', res)

// store.dispatch(initItem(res.data));

// }).catch(() => {

// })

store.dispatch(getToDoList())// 传入的可以是一个函数 该函数返回值可以不是Acton对像 而是一个函数

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值