with no redux-thunk
1.执行同步action
// 同步action
function decrement(){
return { type: 'INCREMENT', payload: 1 }
}
const mapDispatchToProps = (dispatch) => {
return {
increment: () => dispatch({ type: 'INCREMENT', payload: 1}),
decrement: () => dispatch( decrement() )
}
}
2.执行异步action
// 异步action
function decrement(){
return Promise.resolve({type: 'ASYNC_ACTION'})
}
const mapDispatchToProps = (dispatch) => {
return {
decrement: () => dispatch( decrement() ), // ⚠️报错!
decrement2: () => {
/** ♀️只能在这里执行.then,且不能很好将业务代码抽离出来**/
decrement().then(plainObject=>{
dispatch(plainObject)
})
}
}
};
decrement
报错信息:throw new Error: Actions must be plain objects,Use custom middleware for async actions.
at dispatch (createStore.js:152)
dispatch内必须是一个扁平化的object,
或者是能直接返回一个{type:'REDUCERS',payload:data}
的函数
缺点:
在decrement函数中无法获得其他reducers的state值,即getState()
无法直接dispatch一个异步返回值
with redux-thunk
const mapDispatchToProps = (dispatch) => {
return {
increment: () => dispatch(actionThunkify()),
}
};
function actionThunkify(){
return (dispatch, getState)=>{
setTimeout(()=>{
dispatch({ type: 'INCREMENT', payload:"" })
},1000)
}
}
基本实现原理
7行代码实现
redux-thunk
中间件(middleware)改写了redux
的dispatch()
方法
function dispatch(action){
if(typeof action === "function"){
return action(dispatch, getState)
}else {
return action;
}
}
thunkify动机
如同redux-thunk
所写的[1],创建的action creators不再必须返回一个action对象,还允许返回一个function,以便可以延迟dispatch一个action或者直到满足条件时再dispatch。
btw,在Promise
发明之前,常用thunk化来管理异步callback
Usage
兼容异步/同步action
// 派送异步action
dispatch((dispatch)=>{
return dispatch(asyncFunction())
});
// 异步函数
function asyncFunction(){
return (dispatch)=>{
setTimeout(()=>{
dispatch({type:"ASYNC_ACTION"})
},1000)
}
}
// 同步函数
dispatch((dispatch)=>{
return dispatch({type:"SYNC_ACTION"})
});
// 直接对象
dispatch({type:"PLAIN_OBJECT"})
其他
github: https:// github.com/reduxjs/redu x-thunk
同步发布于简书、知乎、微信公众号
关注微信公众号: Github星探 了解更多宝藏库