在 Redux 使用過程中,通常需要重置 store 的狀態(tài),比如應(yīng)用初始化的時(shí)候、用戶退出登錄的時(shí)候,這樣能夠避免數(shù)據(jù)殘留,避免 UI 顯示了上一個(gè)用戶的數(shù)據(jù),容易造成用戶數(shù)據(jù)泄露。
最簡(jiǎn)單的實(shí)現(xiàn)方法就是為每個(gè)獨(dú)立的 store 添加RESET_APP 的 action,每次需要 reset 的時(shí)候,dispatch 這個(gè) action 即可,如下代碼
const usersDefaultState = [];const users = (state = usersDefaultState, { type, payload }) => { switch (type) { case "ADD_USER": return [...state, payload]; default: return state; }};添加 reset action 后:
const usersDefaultState = []const users = (state = usersDefaultState, { type, payload }) => { switch (type) { case "RESET_APP": return usersDefaultState; case "ADD_USER": return [...state, payload]; default: return state; }};這樣雖然簡(jiǎn)單,但是當(dāng)獨(dú)立的 store 較多時(shí),需要添加很多 action,而且需要很多個(gè) dispatch 語句去觸發(fā),比如:
dispatch({ type: RESET_USER });dispatch({ type: RESET_ARTICLE });dispatch({ type: RESET_COMMENT });當(dāng)然你可以封裝一下代碼,讓一個(gè)RESET_DATA 的 action 去觸發(fā)多個(gè) reset 的 action,避免業(yè)務(wù)代碼看上去太亂。
不過本文介紹一種更優(yōu)雅的實(shí)現(xiàn),需要用到一個(gè)小技巧,看下面代碼:
const usersDefaultState = []const users = (state = usersDefaultState, { type, payload }) => {...}當(dāng)函數(shù)參數(shù) state 為 undefined 時(shí),state 就會(huì)去 usersDefaultState 這個(gè)默認(rèn)值,利用這個(gè)技巧,我們可以在 rootReducers 中檢測(cè) RESET_DATA action,直接賦值 undefined 就完成了所有 store 的數(shù)據(jù)重置。實(shí)現(xiàn)代碼如下:
我們通常這樣導(dǎo)出所有的 reducers
// reducers.jsconst rootReducer = combineReducers({ /* your app's top-level reducers */}) export default rootReducer;先封裝一層,combineReducers 返回 reducer 函數(shù),不影響功能
// reducers.jsconst appReducer = combineReducers({ /* your app's top-level reducers */})const rootReducer = (state, action) => { return appReducer(state, action)}export default rootReducer;檢測(cè)到特定重置數(shù)據(jù)的 action 后利用 undefined 技巧 (完整代碼)
// reducers.jsconst appReducer = combineReducers({ /* your app's top-level reducers */})const rootReducer = (state, action) => { if (action.type === 'RESET_DATA') { state = undefined } return appReducer(state, action)}參考:
Resetting Redux State with a Root Reducer
How to reset the state of a Redux store?
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯(cuò)新站長(zhǎng)站。
新聞熱點(diǎn)
疑難解答
圖片精選