如何使用 'combineReducers' 将 Redux 状态转换为 Redux Persist?

How to transform a Redux state into Redux Persist using 'combineReducers'?

我尝试在 Redux-Persist 中转换我的 Redux 状态,但我不知道如何编写代码,因为我使用 combineReducers。

这是我店的样子:

import { createStore, combineReducers } from 'redux'
import { usersReducer } from './users';
import { eventsReducer } from './events';

export const store = createStore(combineReducers({
    users: usersReducer,
    events: eventsReducer
}));

这是一家商店的样子:

const initialState = {
    loggedIn: false,
    thisUser: []
}

export function usersReducer(state = initialState, action) {
    switch (action.type) {
        case 'users/loggedIn':
            return { ...state, loggedIn: action.payload }
        case 'users/addUser':
            return { ...state, thisUser: action.payload[0] }
        case 'users/setActivated':
            return { ...state, thisUser: { ...state.thisUser, activated: action.payload } }
        case 'clearAll':
            return {
                thisUser: []
            }
        default:
            return state
    }
}

有人可以帮我吗?

您只需更改 store.js 中的代码即可。

Pre-requisite

  1. 安装@reduxjs/toolkit
  • 使用 npmnpm install @reduxjs/toolkit
  • 使用yarnyarn add @reduxjs/toolkit
  1. 安装redux-persist
  • 使用 npmnpm install redux-persist
  • 使用yarnyarn add redux-persist

要在 store.js 文件中进行的更改

1。保留所有减速器

import { combineReducers } from 'redux'
import { configureStore } from '@reduxjs/toolkit'
import { usersReducer } from './users';
import { eventsReducer } from './events';
import {
  FLUSH, PAUSE,
  PERSIST, persistReducer, PURGE,
  REGISTER, REHYDRATE
} from 'redux-persist';
import storage from 'redux-persist/lib/storage';

// combine all reducers
const reducers = combineReducers({
  users: usersReducer,
  events: eventsReducer
})

export const store = configureStore({
  reducer: persistReducer(
    {
      key: 'root',
      storage
    },
    reducers
  ),
  middleware: getDefaultMiddleware => getDefaultMiddleware({
    serializableCheck: {
      ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER]
    }
  })
})

3。仅保留某些减速器

import { combineReducers } from 'redux'
import { configureStore } from '@reduxjs/toolkit'
import { usersReducer } from './users';
import { eventsReducer } from './events';
import {
  FLUSH, PAUSE,
  PERSIST, persistReducer, PURGE,
  REGISTER, REHYDRATE
} from 'redux-persist';
import storage from 'redux-persist/lib/storage';

// combine all reducers
const reducers = combineReducers({
  users: persistReducer(
    {
      key: 'users',
      storage
    },
    usersReducer
  ),
  events: eventsReducer
})

export const store = configureStore({
  reducer: reducers,
  middleware: getDefaultMiddleware => getDefaultMiddleware({
    serializableCheck: {
      ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER]
    }
  })
})

参考文献如下: