您好,登錄后才能下訂單哦!
這篇文章主要介紹如何實現(xiàn)重置Redux狀態(tài)數(shù)據(jù)的方法,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
在 Redux 使用過程中,通常需要重置 store 的狀態(tài),比如應用初始化的時候、用戶退出登錄的時候,這樣能夠避免數(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è)務代碼看上去太亂。
不過本文介紹一種更優(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)代碼如下:
我們通常這樣導出所有的 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) }
以上是“如何實現(xiàn)重置Redux狀態(tài)數(shù)據(jù)的方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。