当前位置: 代码迷 >> 综合 >> redux-thunk的配置和使用
  详细解决方案

redux-thunk的配置和使用

热度:91   发布时间:2024-01-10 19:17:31.0

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.dataconst action = initListAction(data)dispatch(action)})}
}

调用上面的函数:

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