一、作用
redux-thunk 可以处理 函数形式 的action.从而就可以在函数形式的action中执行异步操作代码.
使用前:
actions/
const action1 = {type: 'todos/add', payload: '学习redux'}
// 组件使用
dispatch(action1)
使用后:
actions/
const action1 = async (dispatch) =>{
const res = await 异步动作()
dispatch({type: 'todos/add', payload: '学习redux'})
}
//组件使用
dispatch(action1)
二、步骤
1.安装:npm i redux-thunk
2.使用:store/index.js
1)导入 redux-thunk , applyMiddleware
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
2)调用applyMiddleware将 thunk 添加到中间件列表中
const store = createStore(rootReducer, applyMiddleware(thunk))
3)修改 action creator,返回一个函数,其形参就是redux的dispatch
./src/store/actions/
const addTodo = (name)=> {
return async (dispatch) =>{
const res = await 异步动作()
dispatch({type: 'todos/add', payload: name})
}
}
//组件使用action不要忘记导入
dispatch(addTodo('学习redux'))