重置Redux的狀態(tài)數(shù)據(jù)的方法實現(xiàn)
在 Redux 使用過程中,通常需要重置 store 的狀態(tài),比如應(yīng)用初始化的時候、用戶退出登錄的時候,這樣能夠避免數(shù)據(jù)殘留,避免 UI 顯示了上一個用戶的數(shù)據(jù),容易造成用戶數(shù)據(jù)泄露。
最簡單的實現(xiàn)方法就是為每個獨立的 store 添加RESET_APP 的 action,每次需要 reset 的時候,dispatch 這個 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;
}
};
這樣雖然簡單,但是當獨立的 store 較多時,需要添加很多 action,而且需要很多個 dispatch 語句去觸發(fā),比如:
dispatch({ type: RESET_USER });
dispatch({ type: RESET_ARTICLE });
dispatch({ type: RESET_COMMENT });
當然你可以封裝一下代碼,讓一個RESET_DATA 的 action 去觸發(fā)多個 reset 的 action,避免業(yè)務(wù)代碼看上去太亂。
不過本文介紹一種更優(yōu)雅的實現(xiàn),需要用到一個小技巧,看下面代碼:
const usersDefaultState = []
const users = (state = usersDefaultState, { type, payload }) => {...}
當函數(shù)參數(shù) state 為 undefined 時,state 就會去 usersDefaultState 這個默認值,利用這個技巧,我們可以在 rootReducers 中檢測 RESET_DATA action,直接賦值 undefined 就完成了所有 store 的數(shù)據(jù)重置。實現(xiàn)代碼如下:
我們通常這樣導(dǎo)出所有的 reducers
// reducers.js
const rootReducer = combineReducers({
/* your app's top-level reducers */
})
export default rootReducer;
先封裝一層,combineReducers 返回 reducer 函數(shù),不影響功能
// reducers.js
const appReducer = combineReducers({
/* your app's top-level reducers */
})
const rootReducer = (state, action) => {
return appReducer(state, action)
}
export default rootReducer;
檢測到特定重置數(shù)據(jù)的 action 后利用 undefined 技巧 (完整代碼)
// reducers.js
const 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?
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JS判斷不同分辨率調(diào)用不同的CSS樣式文件實現(xiàn)思路及測試代碼
最近看一個網(wǎng)站,發(fā)現(xiàn)顯示器不同的分辨率,樣式文件調(diào)用的也不一樣,于是很好奇研究并寫了一個,經(jīng)測試感覺還不錯,感興趣的你可以來看看哦2013-01-01
javascript制作sql轉(zhuǎn)換為stringBuffer的小工具
這篇文章主要介紹了javascript制作sql轉(zhuǎn)換為stringBuffer的小工具,使用方法很簡單,吧寫好的sql語句只要格式化好之后放進去就可以了,推薦給大家,有需要的小伙伴可以參考下。2015-04-04
JS函數(shù)內(nèi)部屬性之a(chǎn)rguments和this實例解析
在函數(shù)內(nèi)部,有兩個特殊的對象:arguments和this。這篇文章主要介紹了函數(shù)內(nèi)部屬性之a(chǎn)rguments和this ,需要的朋友可以參考下2018-10-10

