redux-thunk的配置和使用

1、安装thunk

npm install redux-thunk --save
或
yarn add redux-thunk

2、创建store时引入中间键和配置(参照官方文档)

首先需要在创建store时引入applyMiddleware方法和thunk:

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

通过enhancer将参数传递给createStore,既使用了thunk又使用了调试工具redux-devtools,总体代码如下:

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

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

配置完毕就可以在store里面写异步代码(axios等)。

3、使用thunk

原本的actionCreators中返回的是个对象,引用redux-thunk后action不仅仅可以是个对象,还可以是函数。

原本只能说如下:

export const initListAction = (data) => ({
	type: INIT_LIST_ACTION,
	data
})

使用thunk后,actionCreators的action可以是个函数,如果return的是一个函数就会自动接收一个dispatch方法,axios请求结果获得后,再去走上面的reducer流程,代码如下:

export const getTodoList = () => {
	return (dispatch) => {
		axios.get('/list.json').then(res => {
			const data = res.data
			const action = initListAction(data)
			dispatch(action)
		})
	}
}

调用上面的函数:

componentDidMount() {
	const action = getTodoList() // 此处返回的action为一个函数
	store.dispatch(action)
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值