在 Redux 使用过程当中,一般须要重置 store 的状态,好比应用初始化的时候、用户退出登陆的时候,这样可以避免数据残留,避免 UI 显示了上一个用户的数据,容易形成用户数据泄露。
最简单的实现方法就是为每一个独立的 store 添加RESET_APP
的 action,每次须要 reset 的时候,dispatch 这个 action 便可,以下代码javascript
const usersDefaultState = []; const users = (state = usersDefaultState, { type, payload }) => { switch (type) { case "ADD_USER": return [...state, payload]; default: return state; } };
添加 reset action 后:java
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 语句去触发,好比:redux
dispatch({ type: RESET_USER }); dispatch({ type: RESET_ARTICLE }); dispatch({ type: RESET_COMMENT });
固然你能够封装一下代码,让一个RESET_DATA 的 action 去触发多个 reset 的 action,避免业务代码看上去太乱。 app
不过本文介绍一种更优雅的实现,须要用到一个小技巧,看下面代码:函数
const usersDefaultState = [] const users = (state = usersDefaultState, { type, payload }) => {...}
当函数参数 state 为 undefined 时,state 就会去 usersDefaultState 这个默认值,利用这个技巧,咱们能够在 rootReducers 中检测 RESET_DATA action,直接赋值 undefined 就完成了全部 store 的数据重置。实现代码以下: spa
咱们一般这样导出全部的 reducerscode
// reducers.js const rootReducer = combineReducers({ /* your app’s top-level reducers */ }) export default rootReducer;
先封装一层,combineReducers 返回 reducer 函数,不影响功能ip
// reducers.js const appReducer = combineReducers({ /* your app’s top-level reducers */ }) const rootReducer = (state, action) => { return appReducer(state, action) } export default rootReducer;
检测到特定重置数据的 action 后利用 undefined 技巧 (完整代码)get
// 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?it