我创建了我的应用商店:
import {configureStore} from '@reduxjs/toolkit';
import {persistStore, persistReducer} from 'redux-persist';
import createFilter from 'redux-persist-transform-filter';
import storage from 'redux-persist/lib/storage';
import rootReducer from './rootReducer';
const whiteListFilter = createFilter('references', 'label');
const persistConfig = {
key: 'root',
storage,
whiteListFilter,
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = configureStore({
reducer: persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: false,
}),
});
const persistor = persistStore(store);
export {store, persistor};
和referenceSlice.js:
import {createSlice} from "@reduxjs/toolkit"
const initialState = {
label: '',
references: [],
error: '',
}
const referenceSlice = createSlice({
name: 'reference',
initialState,
reducers: {
updateReference(state, action){
state = Object.assign(state, action.payload);
}
}
});
export default referenceSlice.reducer;
export const {updateReference} = referenceSlice.actions
Presentation.jsx:
import React from 'react';
import {useDispatch} from 'react-redux';
import {updateReference} from 'referenceSlice';
const Presenter = () => {
const dispatch = useDispatch();
const [label, setLabel] = React.useState('');
const [error, setError] = React.useState('');
const [touched, setTouched] = React.useState(false);
const handleChange = (e) => {
setLabel(e.target.value);
}
const handleBlur = (e) => {
setTouched(true)
if(e.target.value) {
dispatch(updateReference(label));
}else {
setError('required*')
}
}
return(
<div>
<TextField
label='Reference label'
onChange={handleChange}
onBlur={handleBlur}
helperText={touched && error ? error : ''}
/>
<OtherComponent />
</div>
);
export default Presenter;
这里的问题是,我只想保留来自引用reducer的某些属性,但是在这种情况下,整个reducer都保留了。我该如何解决?
答案 0 :(得分:0)
Redux-persist在白名单过滤器中寻找一个数组,这些必须是您的rootReducer中的键名。
请参见https://github.com/rt2zz/redux-persist#blacklist--whitelist
// WHITELIST
const persistConfig = {
key: 'root',
storage: storage,
whitelist: ['navigation'] // only navigation will be persisted
};
还要注意,可以将嵌套属性黑名单,只是有点怪异的方式,您需要将完整的reducer列入黑名单,并为被列入黑名单的reducer创建一个单独的配置,该配置仅将某些属性黑名单。