我正在使用redux-form,它提供了一个内置的reducer,称为“formReducer”,需要在组合的reducer中注册,以使用redux的存储来管理表单状态。
我也使用redux-persist来持久存储redux。
当我不想让表单自动重新填充用户在页面重新加载或页面刷新时输入的数据时引发的问题。在我自己编写的普通reducer中,我可以简单地为“REHYDRATE”类型的操作添加一个switch case(由redux-persit调度),以防止状态切片仅通过返回其初始状态或空状态来自动补水。但是redux-form的formReducer是由redux-form提供的,所以我无法改变。那么,有没有办法“自定义”redux-form reducer来添加那个switch case?或者,有没有什么方法可以配置redux-persist来不自动补充特定的状态切片,或者有什么方法可以将redux-form配置为不通过页面重新加载或页面刷新自动填充?
答案 0 :(得分:2)
我有一个完美的"解决方案基于@jpdelatorre在此帖子How to handle redux-form/CHANGE in reducer
中提出的建议基本上它是"延伸"由redux-form提供的formReducer,然后为事件添加switch case" REHYDRATE":
import { reducer as reduxFormReducer } from 'redux-form'
import { REHYDRATE } from 'redux-persist/constants'
const formPlugin = {
my_redux_form_name: (state, action) => {
switch (action.type) {
case REHYDRATE:
return {}
default:
return state
}
}
}
const formReducer = reduxFormReducer.plugin(formPlugin)
export default formReducer
然后让扩展的reducer注册到root reducer。
import formReducer from './form.reducer'
const rootReducer = combineReducers({
...other reducers,
form: formReducer
})
答案 1 :(得分:1)
您可以使用Middleware来处理此特定操作类型,并防止将其传递给reducer。
const myMiddleWare = store => next => action => {
if(action.type != 'REHYDRATE'){
next(action); // pass the action forward to the reducers
} else{
// do your logic here, you can use store.dispatch to dispatch other actions
// when your not invoking next(action) this action won't pass through to all the reducers
}
}
答案 2 :(得分:1)
如果您正在使用最新的(v5)redux-persist版本,则在persistConfig选项中有一个白名单键选项,您可以在其中将哪些还原剂持久化/补水白名单。您应该使用它,例如:
const persistConfig = {
key: 'root_key_in_localstorage',
storage,
whitelist: ['session'],
}