前言:对于复杂的action,如ajax异步请求后修改store,建议使用 redux-thunk 来简化 action
1、下载 redux-thunk 和配置 redux-thunk
npm i redux-thunk
- 基本配置,在
./store/index.js
中配置
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';
const store = createStore(rootReducer, applyMiddleware(thunk));
- 在使用 redux-devtools 插件同时使用 redux-thunk,在
./store/index.js
中配置
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
2、使用 redux-thunk
- 这时候
action就可以是一个函数
了,不用重新在外面定义一个拿到数据后在dispatch,更有整体性
componentDidMount(){
const action = (dispatch) => {
const list = [1,2,3]
const action = {
type: 'init_list',
list
}
dispatch(action)
}
store.dispatch(action)
}
- 在 actionCreators 中使用 redux-thunk
export const initList = () => {
return (dispatch) => {
const list = [1,2,3]
const action = {
type: 'init_list',
list
}
dispatch(action)
}
}
componentDidMount(){
const action = initList()
store.dispatch(action)
}