仅保留Reducer中的某些字段

时间:2018-09-04 07:31:55

标签: javascript reactjs redux redux-form redux-persist

您好,我们的应用中有一个减速器模式:

{
   data: //here we have our actual data
   fetching: // is it still fetching 
   intact: // has it been 'touched'
   error: //errors if need be
}

此外,由于业务需求,我需要保留ReduxForm,它是蠕虫自身的罐头...

form: {
    Foobar: {
      values: {

      },
      initial: {

      },
      syncErrors: {

      },
      registeredFields: {

      }
    }
  }
}
正如您可能已经发现的,

除了数据之外,持久化任何数据都是没有意义的,但是Redux-Persist可以持久化整个reducer。关于过滤和转换的示例有点...我觉得很乏味,我一直在努力实现。寻找一个例子

2 个答案:

答案 0 :(得分:1)

可以在redux-persist中将密钥列入白名单/黑名单:

import { createStore } from 'redux'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'

const persistConfig = {
  key: 'form',
  storage: storage,
  whitelist: ['Foobar'] // only Foobar will be persisted
};

const persistedReducer = persistReducer(persistConfig, rootReducer)

export default () => {
  let store = createStore(persistedReducer)
  let persistor = persistStore(store)
  return { store, persistor }
}

不幸的是,白名单/黑名单仅接受1级深度,因此我认为您需要使用以下内容:https://github.com/edy/redux-persist-transform-filter或以可以绕过1级的方式重做数据结构库的深层限制。

希望有帮助!

答案 1 :(得分:1)

好的,所以这可以使用redux-persist-transform-filter,例如@NickHTTPS sugested:

import createFilter from 'redux-persist-transform-filter';

const saveSubsetFilter = createFilter('form', ['Foo.bar']);

const persistConfig = {
    key: 'form',
    storage,
    whitelist: ['form'],
    transforms: [saveSubsetFilter]
};

persistCombineReducers(persistConfig, { form: formReducer });

像魅力一样工作:)