如何使redux-persist进入嵌套状态黑名单?

时间:2019-10-21 10:00:59

标签: reactjs react-native redux-persist

这是我的persistConfigstore的代码,我想为blacklist添加tracking,但不为所有跟踪状态添加,而仅为{{1} },tracking.checkingOuttracking.checkingIn,如何正确执行此操作?我了解,如果我想完全删除跟踪,则需要在tracking.searching内写blacklist: ['tracking'],但是我不确定在嵌套状态下该怎么做。

persistConfig

如果我要添加这样的黑名单:blacklist:['tracking.checkingOut','tracking.checkingIn','tracking.searching']会起作用吗?还是应该有不同的方法?

2 个答案:

答案 0 :(得分:1)

您可以在减速器树中更深入地使用persistReducer

combineReducers({
  location,
  i18n,
  tracking: persistReducer({ key: 'tracking', storage: AsyncStorage, blacklist: ['whateverYouWantTo'] }),
})

redux-persist-https://github.com/rt2zz/redux-persist#nested-persists

的官方文档中有一个示例

答案 1 :(得分:0)

如果我们使用@KacperWiszczuk的答案,我不知道是否有可能对整个状态进行完全受控的迁移,因此我的变体是:

如果您想为该州的任何部分制作黑名单,可以从'redux-persist'

中应用 createTransform

示例:

import AsyncStorage from '@react-native-community/async-storage'
import { combineReducers } from 'redux'
import { persistReducer, createTransform } from 'redux-persist'

import localeReducer from './localeReducer' //reducer
import passengerReducers from './passenger' //a set of reducers created via combineReducers

import migrations from './migrations'

const passengerBlacklist = createTransform(
  null,
  (state, key) => {
    {/* Put the code for the initial data here.
        It means when the app will be reopened next 
        data will be cleared/filled up.
    */}
    {/* If you want to not clear but remove the keys, 
        you can use for example omit from 'lodash/omit' here, 
        or any tools what you want
    */}
    const newState = {...state}
    newState.order.from = '' 
    newState.order.to = ''
    return newState
  },
 { whitelist: ['passenger'] }
)

const rootConfig = {
  key: '_store_',
  version: 0,
  storage: AsyncStorage,
  blacklist: [],
  transforms: [passengerBlacklist],
  migrate: migrations,
}

const rootReducer = combineReducers({
  locale: localeReducer,
  passenger: passengerReducers,
})

export default persistReducer(rootConfig, rootReducer)

其中 passengerReducers

import { combineReducers } from 'redux'

import orderReducer from './orderReducer'

export default combineReducers({
  order: orderReducer,
})

这是整个状态的样子

enter image description here