登录时,我正在尝试保存reducerauth
。我的问题不是登录时要保存auth
中的所有值,我只想保存infos
和token
。
请检查下面的代码authReducer
const authReducer = (state = initialState, action) => {
switch (action.type) {
case authConstants.LOGIN_REQUEST:
return {
...state,
token: null,
infos: null,
isLoggedIn: false,
errors: null,
isLoading: true,
};
case authConstants.LOGIN_SUCCESS:
return {
...state,
token: action.payload.token,
infos: action.payload.user[0],
isLoggedIn: true,
errors: null,
isLoading: false,
};
case authConstants.LOGIN_FAILED:
return {
...state,
token: null,
infos: null,
isLoggedIn: false,
errors: null,
isLoading: false,
};
case authConstants.LOGOUT:
return {
...state,
token: null,
infos: null,
isLoggedIn: false,
errors: null,
isLoading: false,
};
default:
return state;
}
};
export default authReducer;
指数
import auth from './authReducer';
import { combineReducers } from 'redux';
import user from './userReducer';
const combinedReducer = combineReducers({
auth,
user,
});
const rootReducer = (state, action) => {
if (action.type === 'Auth/LOGOUT') {
state = undefined;
}
return combinedReducer(state, action);
};
export default rootReducer;
store.js
// Redux
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
// Redux Dev Tools
import { composeWithDevTools } from 'redux-devtools-extension';
// Redux Persist
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
const persistConfig = {
key: 'auth',
storage: storage,
whitelist: ['auth.infos', 'auth.token'], // which reducer want to store
};
const pReducer = persistReducer(persistConfig, rootReducer);
const middleware = [thunk];
const store = createStore(pReducer, composeWithDevTools(applyMiddleware(...middleware)));
const persistor = persistStore(store);
export { persistor, store };
首先创建一个函数,该函数将有助于持久化/白名单状态的某些部分。即
import storage from "redux-persist/lib/storage";
import { persistReducer } from "redux-persist";
export default function persist(key, whitelist, reducer) {
return persistReducer(
{
key,
storage,
whitelist
},
reducer
);
}
之后,您可以使用authReducer中的函数。
import persist from 'path/to/persist';
const authReducer = (state = initialState, action) => {
// other code
}
export default persist('auth', ['infos', 'token'], authReducer);
现在,您可以从存储中删除persistConfig
和persistReducer
。
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
// Redux Dev Tools
import { composeWithDevTools } from 'redux-devtools-extension';
// Redux Persist
import { persistStore } from 'redux-persist';
const middleware = [thunk];
const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(...middleware)));
const persistor = persistStore(store);
export { persistor, store };
信用