首页 文章

如何通过redux-persit自动补水来阻止redux-form的“形式”状态

提问于
浏览
4

我正在使用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配置为不通过页面重新加载或页面刷新自动填充?

3 回答

  • 1

    我有一个"perfect"解决方案,基于@jpdelatorre从这个帖子的建议How to handle redux-form/CHANGE in reducer

    基本上它是“扩展”由redux-form提供的formReducer,然后为事件“REHYDRATE”添加switch case:

    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
    })
    
  • 2

    您可以使用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
      }
    }
    
  • 1

    如果您使用的是最新的(v5)redux-persist版本,则在persistConfig选项中有一个白名单密钥选项,您可以在其中将哪些reducer应该保留/重新水化 . 你应该使用它,例如:

    const persistConfig = { key: 'root_key_in_localstorage', storage, whitelist: ['session'], }

相关问题