with no redux-thunk
-
执行同步action
// 同步action function decrement(){ return -1 } const mapDispatchToProps = (dispatch) => { return { increment: () => dispatch({ type: 'INCREMENT', payload: 1}), decrement: () => dispatch( decrement() ) } }
-
执行异步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)
}else {
return action;
}
}
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/redux-thunk
同步发布于简书、知乎、微信公众号
关注微信公众号:Github星探 了解更多宝藏库
网友评论