Open Manjushaka opened 6 years ago
Redux初探与异步数据流 介绍有部分redux-thunk源码,不是很懂,后续继续研习吧。
让action creator返回一个函数,而不是一个action。返回的这个函数可以接收store的dispatch和getState方法。 实现异步dispatch:
const INCREMENT_COUNTER = 'INCREMENT_COUNTER';
function increment() { return { type: INCREMENT_COUNTER }; }
function incrementAsync() {
return dispatch => {
setTimeout(() => {
// Yay! Can invoke sync or async actions with dispatch
dispatch(increment());
}, 1000);
};
}
实现条件dispatch:
function incrementIfOdd() { return (dispatch, getState) => { const { counter } = getState();
if (counter % 2 === 0) {
return;
}
dispatch(increment());
}; }
3. A thunk is a function that wraps an expression to delay its evaluation.
// calculation of 1 + 2 is immediate // x === 3 let x = 1 + 2;
// calculation of 1 + 2 is delayed // foo can be called later to perform the calculation // foo is a thunk! let foo = () => 1 + 2;
export function fetchData(url) { return (dispatch, getState) => { dispatch(getUserQuest()); return axios(url).then(res => { if (res.status === 200) { return dispatch(getUserSuccess({ data: res.data, })); } else { return dispatch(getUserFailure({ error: 'error', })); } }, err => { return dispatch(getUserFailure({ error: 'error', })); }); }; }
redux-logger:
打印state日志信息。