React native + redux-persist:如何忽略键(黑名单)?

IT技术 javascript reactjs react-native redux react-redux
2021-04-28 13:08:09

我正在存储我的设置,redux-persist并希望忽略其中的一些设置,以便在每次重新启动时重置它们,例如在崩溃后。

可以将一个减速器名称数组添加为blacklistor whitelist,但我想忽略特定的键,例如settings.isLoggedIn代替settings.

// ...
function configureStore(initialState) {
    const store = createStore(
        RootReducer,
        initialState,
        enhancer
    );

    persistStore(store, {
        storage: AsyncStorage,
        blacklist: ['router', 'settings'] // works, 'settings.isLoggedIn' doesn't.
    }, () => {
        // restored
    });

    return store;
}
// ...

我是否必须创建另一个减速器或是否有人解决此问题?

提前致谢!

4个回答

根据文档,黑名单参数包含:“要忽略的键(读取:reducers)”,因此恐怕无法实现您想要的行为。您可以尝试自己实现该功能,但我认为该包的代码库真正侧重于将 reducer 而不是属性列入黑名单(请参阅)。恐怕唯一的解决方案是为您的非持久键创建一个单独的减速器(根据我的经验,这并不麻烦)。

使用转换来保存单独的字段,例如username在 redux-form MyForminside 中state.form.MyForm

const formName = `MyForm`

const formTransform = createTransform(
  (inboundState, key) => {
    return {
      ...inboundState,
      [formName]: {
        values: {
          username: _.get(inboundState, `${ MyForm }.values.username`)
        }
      }
    }
  },
  (outboundState, key) => {
    return outboundState
  },
  { whitelist: [`form`] }
)

persistStore(store, {
  whitelist: [
    `form`
  ],
  transforms: [
    formTransform
  ]
})

您可以为此使用嵌套持久化

import { persistStore, persistReducer } from 'redux-persist';


const rootPersistConfig = {
  key: 'root',
  storage: storage,
  blacklist: ['auth']
}

// here you can tell redux persist to ignore loginFormData from auth reducer

const authPersistConfig = {
  key: 'auth',
  storage: storage,
  blacklist: ['loginFormData']
}

// this is your global config
const rootReducer = combineReducers({
  auth: persistReducer(authPersistConfig, authReducer),
  other: otherReducer,
})

// note: for this to work, your authReducer must be inside blacklist of 
// rootPersistConfig

const myReducerConfig = {
  key: "cp",
  storage: storage,
  blacklist: ["authReducer"],
  debug: true
};


您必须为要保存的每个props创建减速器。