先貼官網(wǎng)鏈接:https://github.com/gaearon/redux-thunk
簡(jiǎn)單的邏輯:
首先刻盐,這是個(gè)關(guān)于action creator的解釋。
什么是action creator降传?返回action的函數(shù)舶治。為什么要用action creator恶座?圖個(gè)方便吧:
/* 使用前 */
// 這里
dispatch({
type: ‘change_name’,
name: ‘Peter’,
});
// 那里
dispatch({
type: ‘change_name’,
name: ‘Ryan’,
});
/* ******************************** */
/* 使用后 */
// 這里
dispatch(changeName(‘Peter’));
// 那里
dispatch(changeName(‘Ryan’));
Thunk的做法就是擴(kuò)展了這個(gè)action creator便脊。
Redux官網(wǎng)說蚂四,action就是Plain JavaScript Object光戈。Thunk允許action creator返回一個(gè)函數(shù)哪痰,而且這個(gè)函數(shù)第一個(gè)參數(shù)是dispatch遂赠。
這不是鬧呢?
所以不光改造action creator晌杰,如果你要用thunk跷睦,你還要把它放進(jìn)middleware里去,這樣函數(shù)類型的action就被thunk middleware捕獲肋演,根據(jù)你的函數(shù)邏輯抑诸,再去dispatch常規(guī)的action。
這樣Async Action其實(shí)就是發(fā)Ajax之前dispatch一發(fā)爹殊,收到服務(wù)器相應(yīng)后dispatch一發(fā)蜕乡,報(bào)錯(cuò)的話再來dispatch一發(fā)。為什么用梗夸?圖個(gè)方便吧:
/**
* Sample Async Action namely: the thunk
* 要配合redux-thunk這個(gè)middleware一起食用
* ref: https://github.com/gaearon/redux-thunk
*/
export const loadMoreWorkAsync = () => dispatch => {
/* TODO: 請(qǐng)暫時(shí)無(wú)視我如此拙劣的dispatch行為 */
/* 1. fetch之前层玲,可以先發(fā)個(gè)pending的action */
dispatch({
type: LOAD_MORE_WORK,
msg: 'pending',
});
fetch('imgs/test.json').then(resp => {
// console.log('[resp]', resp.status);
if (resp.status === 200) return resp.json();
throw new Error('not 200 this time'); // 美滴很
}).then(json => {
/* 2. 異步結(jié)束了,發(fā)結(jié)果action */
dispatch({
type: LOAD_MORE_WORK,
msg: json.name,
});
}).catch(error => {
/* 3. 倒霉催的反症,發(fā)報(bào)錯(cuò)action */
dispatch({
type: LOAD_MORE_WORK,
msg: error,
});
});
};