|
導讀網頁的本質就是超級文本標記語言,通過結合使用其他的Web技術(如:腳本語言、公共網關接口、組件等),可以創造出功能強大的網頁。因而,超級文本標記語言是萬維網(Web)編程的基礎,也就是說萬維網是建立... 網頁的本質就是超級文本標記語言,通過結合使用其他的Web技術(如:腳本語言、公共網關接口、組件等),可以創造出功能強大的網頁。因而,超級文本標記語言是萬維網(Web)編程的基礎,也就是說萬維網是建立在超文本基礎之上的。超級文本標記語言之所以稱為超文本標記語言,是因為文本中包含了所謂“超級鏈接”點。 本篇文章給大家帶來的內容是關于redux異步操作的詳細介紹(代碼示例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。一、redux基礎 redux
react-redux 二、redux處理異步的中間件 redux-thunk 三、redux-request-async-middleware 先從redux文檔中的異步action說起,每個接口調用需要dispatch三個同步action,分別是: dispatch(fetchPostsRequest(subject));
fetch(url).then(res => {
dispatch(fetchPostsSuccess(subject, res));
}).catch(e => {
dispatch(fetchPostsFailure(subject, e));
})只是將這個操作封裝進中間件里,特殊的地方在于:
中間件源碼 export const reduxRequest = store => next => action => {
let result = next(action);
let { type, subject, model } = action;
let _next = action.next;
if(type === FETCH_POSTS_REQUEST) {
model().then(response => {
_next && _next(response);
store.dispatch(fetchPostsSuccess(subject, response));
}).catch(error => {
console.error(error);
store.dispatch(fetchPostsFailure(subject, error));
});
}
return result
};/
reducer源碼 export const requests = (state = {}, action) => {
switch (action.type) {
case FETCH_POSTS_REQUEST:
return assign({},
state,
{
[action.subject]: {
isFetching: true,
state: 'loading',
subject: action.subject,
response: null,
error: null,
}
}
);
case FETCH_POSTS_FAILURE:
return assign({},
state,
{
[action.subject]: {
isFetching: false,
state: 'error',
subject: action.subject,
response: state[action.subject].response,
error: action.error,
}
}
);
case FETCH_POSTS_SUCCESS:
return assign({},
state,
{
[action.subject]: {
isFetching: false,
state: 'success',
subject: action.subject,
response: action.response,
}
}
);
case FETCH_POSTS_CLEAR:
return assign({},
state,
{
[action.subject]: {
isFetching: false,
state: 'cleared',
subject: null,
response: null,
error: null,
}
}
)
return state;
}
}
將請求進行封裝 const request = (subject, model, next) => {
_dispatch(fetchPostsRequest(subject, model, next));
return true;
};
將結果進行封裝 const getResponse = state =>
state
&& state.response !== null
&& state.response;
const getLoading = (states = []) =>
states.reduce((pre, cur) =>
pre || (cur && cur.isFetching)
, false)
|| false;
四、總結
以上就是redux異步操作的詳細介紹(代碼示例)的詳細內容,更多請關注php中文網其它相關文章! 網站建設是一個廣義的術語,涵蓋了許多不同的技能和學科中所使用的生產和維護的網站。 |
溫馨提示:喜歡本站的話,請收藏一下本站!