redux-thunk的配置和使用

版权声明:本文为博主原创文章,请随意转载。。。 https://blog.csdn.net/scorpio_h/article/details/86409012

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)
}

猜你喜欢

转载自blog.csdn.net/scorpio_h/article/details/86409012