如何重置 Redux 存储的状态
How to reset the state of a Redux store?
我正在使用Redux进行状态管理。
如何将商店重置为其初始状态?
例如,假设我有两个用户帐户(u1
和 u2
)。
想象一下以下事件序列:
-
用户
u1
登录到应用程序并执行某些操作,因此我们在存储中缓存了一些数据。 -
用户
u1
注销。 -
用户
u2
登录应用程序而不刷新浏览器。
此时,缓存的数据将与u1
相关联,我想清理它。
如何在第一个用户注销时将 Redux 存储重置为其初始状态?
是在应用程序中编写根化简器。
根化简器通常会将操作的处理委托给combineReducers()
生成的化简器。但是,每当它收到USER_LOGOUT
操作时,它都会再次返回初始状态。
例如,如果您的根化简器如下所示:
const rootReducer = combineReducers({
/* your app’s top-level reducers */
})
您可以将其重命名为 appReducer
并编写委派给它的新rootReducer
:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
return appReducer(state, action)
}
现在我们只需要教新rootReducer
返回初始状态以响应USER_LOGOUT
操作。众所周知,无论操作如何,当使用 undefined
作为第一个参数调用化简器时,它们都应该返回初始状态。让我们利用这个事实在将累积state
传递给appReducer
时有条件地剥离它:
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
return appReducer(undefined, action)
}
return appReducer(state, action)
}
现在,每当USER_LOGOUT
触发时,所有化简器都将重新初始化。如果他们愿意,他们也可以返回与最初不同的内容,因为他们也可以检查action.type
。
重申一下,完整的新代码如下所示:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
return appReducer(undefined, action)
}
return appReducer(state, action)
}
如果您使用的是 redux-persist,您可能还需要清理您的存储。Redux-persist 在存储引擎中保留状态的副本,状态副本将在刷新时从那里加载。
首先,您需要导入相应的存储引擎,然后在将其设置为undefined
并清理每个存储状态键之前分析状态。
const rootReducer = (state, action) => {
if (action.type === SIGNOUT_REQUEST) {
// for all keys defined in your persistConfig(s)
storage.removeItem('persist:root')
// storage.removeItem('persist:otherKey')
return appReducer(undefined, action);
}
return appReducer(state, action);
};
Dan Abramov 的答案是正确的,只是我们在使用 react-router-redux 包和这种方法时遇到了一个奇怪的问题。
我们的解决方法是不将状态设置为 undefined
,而是仍然使用当前的路由缩减器。因此,如果您使用此软件包,我建议您实施以下解决方案
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
const { routing } = state
state = { routing }
}
return appReducer(state, action)
}
定义操作:
const RESET_ACTION = {
type: "RESET"
}
然后在每个化简器中假设您使用switch
或if-else
通过每个化简器处理多个操作。我将把这个案子当作switch
.
const INITIAL_STATE = {
loggedIn: true
}
const randomReducer = (state=INITIAL_STATE, action) {
switch(action.type) {
case 'SOME_ACTION_TYPE':
//do something with it
case "RESET":
return INITIAL_STATE; //Always return the initial state
default:
return state;
}
}
这样,每当调用RESET
操作时,reducer 都会使用默认状态更新存储。
现在,对于注销,您可以处理如下操作:
const logoutHandler = () => {
store.dispatch(RESET_ACTION)
// Also the custom logic like for the rest of the logout handler
}
每次用户登录时,无需刷新浏览器。应用商店将始终处于默认值。
store.dispatch(RESET_ACTION)
只是阐述了这个想法。您很可能会为此目的拥有一个动作创建者。更好的方法是您有一个LOGOUT_ACTION
。
一旦你发送这个LOGOUT_ACTION
.然后,自定义中间件可以使用 Redux-Saga 或 Redux-Thunk 拦截此操作。但是,这两种方式,您都可以调度另一个操作"重置"。这样,商店注销和重置将同步进行,您的商店将准备好其他用户登录。
只是对丹·阿布拉莫夫答案的简化回答:
const rootReducer = combineReducers({
auth: authReducer,
...formReducers,
routing
});
export default (state, action) =>
rootReducer(action.type === 'USER_LOGOUT' ? undefined : state, action);
使用 Redux Toolkit 和/或 Typescript
:const appReducer = combineReducers({
/* your app’s top-level reducers */
});
const rootReducer = (
state: ReturnType<typeof appReducer>,
action: AnyAction
) => {
/* if you are using RTK, you can import your action and use it's type property instead of the literal definition of the action */
if (action.type === logout.type) {
return appReducer(undefined, { type: undefined });
}
return appReducer(state, action);
};
从安全角度来看,注销用户时最安全的做法是重置所有持久状态(例如 cookie、localStorage
、IndexedDB
、Web SQL
等)并使用 window.location.reload()
对页面进行硬刷新。草率的开发人员可能会意外或故意地将一些敏感数据存储在window
、DOM 等上。消除所有持久状态并刷新浏览器是保证不会将来自前一个用户的信息泄露给下一个用户的唯一方法。
(当然,作为共享计算机上的用户,您应该使用"隐私浏览"模式,自己关闭浏览器窗口,使用"清除浏览数据"功能等,但作为开发人员,我们不能指望每个人都总是那么勤奋)
const reducer = (state = initialState, { type, payload }) => {
switch (type) {
case RESET_STORE: {
state = initialState
}
break
}
return state
}
您还可以触发由所有或部分化简器处理的操作,该操作要重置为初始存储。一个操作可以触发重置整个状态,或者只是其中似乎适合您的部分。我相信这是最简单,最可控的方法。
使用 Redux 如果应用了以下解决方案,假设我已经在所有化简器中设置了一个initialState
(例如 { user: { name, email }}
)。在许多组件中,我检查这些嵌套属性,因此通过此修复,我可以防止我的渲染方法在耦合属性条件下被破坏(例如,如果state.user.email
,如果上面提到的解决方案,这将抛出错误user is undefined
)。
const appReducer = combineReducers({
tabs,
user
})
const initialState = appReducer({}, {})
const rootReducer = (state, action) => {
if (action.type === 'LOG_OUT') {
state = initialState
}
return appReducer(state, action)
}
更新 NGRX4
如果要迁移到 NGRX 4,您可能已经从迁移指南中注意到,组合化简器的rootreducer
方法已替换为ActionReducerMap
方法。起初,这种新的做事方式可能会使重置状态成为一项挑战。这实际上很简单,但这样做的方式已经改变。
此解决方案的灵感来自 NGRX4 Github 文档中的元化简器 API 部分。
首先,假设您使用NGRX的新ActionReducerMap
选项组合您的减速器:
//index.reducer.ts
export const reducers: ActionReducerMap<State> = {
auth: fromAuth.reducer,
layout: fromLayout.reducer,
users: fromUsers.reducer,
networks: fromNetworks.reducer,
routingDisplay: fromRoutingDisplay.reducer,
routing: fromRouting.reducer,
routes: fromRoutes.reducer,
routesFilter: fromRoutesFilter.reducer,
params: fromParams.reducer
}
现在,假设您要从app.module
中重置状态
//app.module.ts
import { IndexReducer } from './index.reducer';
import { StoreModule, ActionReducer, MetaReducer } from '@ngrx/store';
...
export function debug(reducer: ActionReducer<any>): ActionReducer<any> {
return function(state, action) {
switch (action.type) {
case fromAuth.LOGOUT:
console.log("logout action");
state = undefined;
}
return reducer(state, action);
}
}
export const metaReducers: MetaReducer<any>[] = [debug];
@NgModule({
imports: [
...
StoreModule.forRoot(reducers, { metaReducers}),
...
]
})
export class AppModule { }
这基本上是使用NGRX 4实现相同效果的一种方法。
我在使用打字稿时的解决方法,建立在 Dan Abramov 的答案之上(redux 类型使得无法将undefined
传递给 reducer 作为第一个参数,所以我将初始根状态缓存在一个常量中):
// store
export const store: Store<IStoreState> = createStore(
rootReducer,
storeEnhacer,
)
export const initialRootState = {
...store.getState(),
}
// root reducer
const appReducer = combineReducers<IStoreState>(reducers)
export const rootReducer = (state: IStoreState, action: IAction<any>) => {
if (action.type === "USER_LOGOUT") {
return appReducer(initialRootState, action)
}
return appReducer(state, action)
}
// auth service
class Auth {
...
logout() {
store.dispatch({type: "USER_LOGOUT"})
}
}
只需清除注销链接会话并刷新页面即可。您的商店不需要额外的代码。任何时候你想要完全重置状态,页面刷新都是一种简单且易于重复的处理方式。
如果您使用的是 redux-actions,这里有一个快速解决方法,使用 HOF(高阶函数)进行handleActions
。
import { handleActions } from 'redux-actions';
export function handleActionsEx(reducer, initialState) {
const enhancedReducer = {
...reducer,
RESET: () => initialState
};
return handleActions(enhancedReducer, initialState);
}
然后用handleActionsEx
代替原来的handleActions
来处理减速器。
Dan的回答给出了关于这个问题的好主意,但对我来说效果不佳,因为我正在使用redux-persist
。
当与redux-persist
一起使用时,简单地传递undefined
状态不会触发持久行为,所以我知道我必须手动从存储中删除项目(在我的例子中是 React Native,因此AsyncStorage
)。
await AsyncStorage.removeItem('persist:root');
或
await persistor.flush(); // or await persistor.purge();
对我也不起作用——他们只是对我大喊大叫。(例如,抱怨"意外的钥匙_persist...")
然后我突然思考,我想要的只是让每个单独的减速器在遇到RESET
动作类型时返回自己的初始状态。这样,持久性就可以自然地处理。显然,如果没有上述实用程序函数(handleActionsEx
),我的代码看起来不会干燥(尽管它只是一个行,即 RESET: () => initialState
),但我受不了了,因为我喜欢元编程。
结合Dan Abramov的答案,Ryan Irilli的答案和Rob Moorman的答案,以解释保持router
状态并初始化状态树中的其他所有内容,我最终得到:
const rootReducer = (state, action) => appReducer(action.type === LOGOUT ? {
...appReducer({}, {}),
router: state && state.router || {}
} : state, action);
我已经创建了清除状态的操作。因此,当我调度注销操作创建者时,我也会调度操作以清除状态。
用户记录操作
export const clearUserRecord = () => ({
type: CLEAR_USER_RECORD
});
注销操作创建者
export const logoutUser = () => {
return dispatch => {
dispatch(requestLogout())
dispatch(receiveLogout())
localStorage.removeItem('auth_token')
dispatch({ type: 'CLEAR_USER_RECORD' })
}
};
还原剂
const userRecords = (state = {isFetching: false,
userRecord: [], message: ''}, action) => {
switch (action.type) {
case REQUEST_USER_RECORD:
return { ...state,
isFetching: true}
case RECEIVE_USER_RECORD:
return { ...state,
isFetching: false,
userRecord: action.user_record}
case USER_RECORD_ERROR:
return { ...state,
isFetching: false,
message: action.message}
case CLEAR_USER_RECORD:
return {...state,
isFetching: false,
message: '',
userRecord: []}
default:
return state
}
};
我不确定这是否是最佳的?
我的看法是防止 Redux 引用初始状态的相同变量:
// write the default state as a function
const defaultOptionsState = () => ({
option1: '',
option2: 42,
});
const initialState = {
options: defaultOptionsState() // invoke it in your initial state
};
export default (state = initialState, action) => {
switch (action.type) {
case RESET_OPTIONS:
return {
...state,
options: defaultOptionsState() // invoke the default function to reset this part of the state
};
default:
return state;
}
};
我创建了一个组件来赋予 Redux 重置状态的能力,您只需使用此组件来增强您的商店并调度特定action.type
来触发重置。实施的想法与丹·阿布拉莫夫在他们的回答中所说的相同。
Github: https://github.com/wwayne/redux-reset
以下解决方案对我有用。
我为元化简器添加了重置状态函数。关键是使用
return reducer(undefined, action);
将所有化简器设置为初始状态。相反,由于商店的结构已被破坏,因此返回undefined
会导致错误。
reducers/index.ts
export function resetState(reducer: ActionReducer<State>): ActionReducer<State> {
return function (state: State, action: Action): State {
switch (action.type) {
case AuthActionTypes.Logout: {
return reducer(undefined, action);
}
default: {
return reducer(state, action);
}
}
};
}
export const metaReducers: MetaReducer<State>[] = [ resetState ];
app.module.ts
import { StoreModule } from '@ngrx/store';
import { metaReducers, reducers } from './reducers';
@NgModule({
imports: [
StoreModule.forRoot(reducers, { metaReducers })
]
})
export class AppModule {}
丹·阿布拉莫夫的回答帮助我解决了我的案子。但是,我遇到了一个情况,即不必清除整个州。所以我这样做了:
const combinedReducer = combineReducers({
// my reducers
});
const rootReducer = (state, action) => {
if (action.type === RESET_REDUX_STATE) {
// clear everything but keep the stuff we want to be preserved ..
delete state.something;
delete state.anotherThing;
}
return combinedReducer(state, action);
}
export default rootReducer;
只是对@dan-abramov答案的扩展,有时我们可能需要保留某些键不被重置。
const retainKeys = ['appConfig'];
const rootReducer = (state, action) => {
if (action.type === 'LOGOUT_USER_SUCCESS' && state) {
state = !isEmpty(retainKeys) ? pick(state, retainKeys) : undefined;
}
return appReducer(state, action);
};
这种方法非常正确:破坏任何特定状态"NAME"以忽略并保留其他状态。
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state.NAME = undefined
}
return appReducer(state, action)
}
为了将状态重置为其初始状态,我编写了以下代码:
const appReducers = (state, action) =>
combineReducers({ reducer1, reducer2, user })(
action.type === "LOGOUT" ? undefined : state,
action
);
我发现丹·阿布拉莫夫的答案对我来说效果很好,但它触发了 ESLint no-param-reassign
错误 - https://eslint.org/docs/rules/no-param-reassign
以下是我如何处理它,确保创建状态的副本(在我的理解中,这是 Reduxy 要做的事情......
import { combineReducers } from "redux"
import { routerReducer } from "react-router-redux"
import ws from "reducers/ws"
import session from "reducers/session"
import app from "reducers/app"
const appReducer = combineReducers({
"routing": routerReducer,
ws,
session,
app
})
export default (state, action) => {
const stateCopy = action.type === "LOGOUT" ? undefined : { ...state }
return appReducer(stateCopy, action)
}
但是,也许创建状态的副本以将其传递给另一个创建该副本的化简器函数有点过于复杂?这读起来不太好,但更切中要害:
export default (state, action) => {
return appReducer(action.type === "LOGOUT" ? undefined : state, action)
}
首先,在我们的应用程序启动时,化简器状态是新的,默认为初始状态。
我们必须添加一个调用 APP 初始加载以保持默认状态的操作。
注销应用程序时,我们可以简单地重新分配默认状态,reducer 将像新的一样工作。
主应用容器
componentDidMount() {
this.props.persistReducerState();
}
主APP减速机
const appReducer = combineReducers({
user: userStatusReducer,
analysis: analysisReducer,
incentives: incentivesReducer
});
let defaultState = null;
export default (state, action) => {
switch (action.type) {
case appActions.ON_APP_LOAD:
defaultState = defaultState || state;
break;
case userLoginActions.USER_LOGOUT:
state = defaultState;
return state;
default:
break;
}
return appReducer(state, action);
};
注销时调用重置状态的操作
function* logoutUser(action) {
try {
const response = yield call(UserLoginService.logout);
yield put(LoginActions.logoutSuccess());
} catch (error) {
toast.error(error.message, {
position: toast.POSITION.TOP_RIGHT
});
}
}
Dan Abramov 的答案没有做的一件事是清除参数化选择器的缓存。如果您有这样的选择器:
export const selectCounter1 = (state: State) => state.counter1;
export const selectCounter2 = (state: State) => state.counter2;
export const selectTotal = createSelector(
selectCounter1,
selectCounter2,
(counter1, counter2) => counter1 + counter2
);
然后,您必须在注销时释放它们,如下所示:
selectTotal.release();
否则,选择器最后一次调用的记忆值和最后一个参数的值仍将在内存中。
代码示例来自 ngrx 文档。
一个对我有用的快速简便的选择是使用 redux-reset .这很简单,并且对于较大的应用程序也有一些高级选项。
在创建商店中设置
import reduxReset from 'redux-reset'
// ...
const enHanceCreateStore = compose(
applyMiddleware(...),
reduxReset() // Will use 'RESET' as default action.type to trigger reset
)(createStore)
const store = enHanceCreateStore(reducers)
在注销功能中调度"重置"
store.dispatch({
type: 'RESET'
})
<</div>
div class="answers"> Redux Toolkit 的方法:
export const createRootReducer = (history: History) => {
const rootReducerFn = combineReducers({
auth: authReducer,
users: usersReducer,
...allOtherReducers,
router: connectRouter(history),
});
return (state: Parameters<typeof rootReducerFn>[0], action: Parameters<typeof rootReducerFn>[1]) =>
rootReducerFn(action.type === appActions.reset.type ? undefined : state, action);
};
为什么不直接使用return module.exports.default()
;)
export default (state = {pending: false, error: null}, action = {}) => {
switch (action.type) {
case "RESET_POST":
return module.exports.default();
case "SEND_POST_PENDING":
return {...state, pending: true, error: null};
// ....
}
return state;
}
注意:请确保将操作默认值设置为 {}
并且没问题,因为您不希望在 switch 语句中检查action.type
时遇到错误。
另一种选择是:
store.dispatch({type: '@@redux/INIT'})
'@@redux/INIT'
是 redux 在您createStore
时自动调度的操作类型,因此假设您的化简器都已经有默认值,这会被这些化简器捕获并重新开始您的状态。不过,它可能被认为是 redux 的私人实现细节,所以买家要当心......
最有效的方法是设置initialState
而不是state
:
const reducer = createReducer(initialState,
on(proofActions.cleanAdditionalInsuredState, (state, action) => ({
...initialState
})),
如果要重置单个减速器
例如
const initialState = {
isLogged: false
}
//this will be your action
export const resetReducer = () => {
return {
type: "RESET"
}
}
export default (state = initialState, {
type,
payload
}) => {
switch (type) {
//your actions will come her
case "RESET":
return {
...initialState
}
}
}
//and from your frontend
dispatch(resetReducer())
- Ember.js-接口状态应该存储在哪里
- 在 React JS 中,什么时候应该使用存储而不是直接操作视图的状态
- 在 Redux 状态下存储具有原型函数的对象
- React + Flux:将初始状态引入存储
- 存储在HTML5存储中的引导崩溃的当前状态
- 通量:多个容器具有相同的存储,不同的状态
- 在 Javascript 中存储对象的当前状态的最佳实践是什么?
- 当存储状态更改时,React 组件不会更新
- 如何重置 Redux 存储的状态
- 使用会话存储复选框的状态
- 将对象存储在 React 组件的状态中
- 如何对 Flux 存储中的状态变量强制执行隐私
- 使用本地存储维护复选框的选中状态
- 将压缩状态存储在“#”之后的 URL 中
- 捕获D3库创建的可视化并将状态存储在DB中
- Ajax和后退按钮.哈希更改,但上一页的状态存储在哪里
- 为什么不将redux存储状态存储在本地组件状态中呢?
- 关于多功能应用的状态存储和通量存储的问题
- 如何将复选框的先前状态存储在多个手风琴中
- IE9状态/存储选择选项将不会追加