source

redux-persist와 redux-toolkit을 설정하는 방법

manycodes 2023. 2. 22. 22:47
반응형

redux-persist와 redux-toolkit을 설정하는 방법

redux-persist는 다음과 같은 기존 react-redux 설정으로 설정했습니다.

onst persistConfig = {
  key: 'root',
  storage,
  whitelist: ['todos'],
};

const persistedReducer = persistReducer(persistConfig, reducer);

const store = createStore(
  persistedReducer,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

const persistor = persistStore(store);

// wrapper
const StateProvider = ({ children }) => {
  return (
    <Provider store={store}>
      <PersistGate loading={<div>Loading...</div>} persistor={persistor}>
        {children}
      </PersistGate>
    </Provider>
  );
};

단, redux-toolkit에서는 어떻게 설정할 수 있습니까?지금까지 이것을 시도했습니다.

const persistedReducer = persistReducer(persistConfig, todoreducer);
const store = configureStore({
  reducer: {
    todos: persistedReducer,
  },
});

const persistor = persistStore(store);

// wrapper
const StateProvider = ({ children }) => {
  return (
    <Provider store={store}>
      <PersistGate loading={<div>Loading...</div>} persistor={persistor}>
        {children}
      </PersistGate>
    </Provider>
  );
};

근데 안 돼요.못 찾겠어todos타고const todos = useSelector(state => state.todos);

정의되지 않은 상태로 반환됩니다.

store.displaces를 설정합니다.

import {configureStore} from '@reduxjs/toolkit';
import storage from 'redux-persist/lib/storage'
import {combineReducers} from "redux"; 
import { persistReducer } from 'redux-persist'
import thunk from 'redux-thunk'

const reducers = combineReducers({
 //...            
});

const persistConfig = {
    key: 'root',
    storage
};

const persistedReducer = persistReducer(persistConfig, reducers);


const store = configureStore({
    reducer: persistedReducer,
    devTools: process.env.NODE_ENV !== 'production',
    middleware: [thunk]
});

export default store;

인덱스 / App.js

import store from './app/store';
import { PersistGate } from 'redux-persist/integration/react'
import { persistStore } from 'redux-persist'

let persistor = persistStore(store);

    <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
        <App/>
        </PersistGate>
    </Provider>,

Redux Toolkit 문서에는 이 문제를 해결하는 데 도움이 되는 가이드와 지속 상태를 정리하고 RTK Query를 사용하는 방법에 대한 조언이 나와 있습니다.

또한 작업 유형을 무시하기 위해 복사하여 붙여넣을 코드도 있습니다.react-persist디스패치그러면 오류 메시지가 더 이상 표시되지 않습니다(오류가 발생하고 있었습니다).A non-serializable value was detected in an action, in the path: `register`.Expo에서 React Native 앱을 실행했을 때)

기입시의 코드 샘플은 다음과 같습니다.

import { configureStore } from '@reduxjs/toolkit'
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from 'redux-persist'
import storage from 'redux-persist/lib/storage'
import { PersistGate } from 'redux-persist/integration/react'

import App from './App'
import rootReducer from './reducers'

const persistConfig = {
  key: 'root',
  version: 1,
  storage,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

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

let persistor = persistStore(store)

ReactDOM.render(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>,
  document.getElementById('root')
)

인스톨 되어 있습니다.

import { configureStore } from "@reduxjs/toolkit";
import storage from "redux-persist/lib/storage";
import { persistReducer } from "redux-persist";
import { combineReducers } from "redux";

const persistConfig = {
  key: "root",
  version: 1,
  storage,
  // if you do not want to persist this part of the state
  blacklist: ['omitedPart']
};

const reducer = combineReducers({
  cart: CartReducer,
  // not persisting this reducer
  omitedPart:OmitReducer
});
// this ensures your redux state is saved to persisted storage whenever it changes
// we pass this to the store
const persistedReducer = persistReducer(persistConfig, reducer);

const store = configureStore({
  reducer: persistedReducer,
});

export default store;

루트 컴포넌트 index.displaces에 있습니다.

import { Provider } from "react-redux";
import store from "./redux/store";
import { PersistGate } from "redux-persist/integration/react";
import { persistStore } from "redux-persist";

let persistor = persistStore(store);

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      //PersistGate delays the rendering of UI until the persisted state has been retrrieved and saved to redux
      <PersistGate persistor={persistor}>
        <App />
      </PersistGate>
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

에서 TypeScript를 사용하는 경우stateReconciles에서 선택하다.persistConfig, 당신은 피하려면 작은 타입의 심이 필요합니다.

  • a)unknown일반적 추론
persistReducer<unknown, AnyAction>

Argument of type 'Reducer<CombinedState<{ ... }>, AnyAction>' is not assignable to parameter of type 'Reducer<unknown, AnyAction>'.
  Types of parameters 'state' and 'state' are incompatible.
    Type 'unknown' is not assignable to type 'CombinedState<{ ... }>'.ts(2345)

  • b) 원형 기준
const persistConfig = {
  stateReconciles: hardSet as RootState,
}

export type RootState = ReturnType<typeof store.getState> // Type alias 'RootState' circularly references itself.

솔루션이 추출된 유형입니다.CombinedState다음과 같습니다.

import type { Reducer } from '@reduxjs/toolkit'
import { configureStore, combineReducers } from '@reduxjs/toolkit'
import { persistStore, persistReducer } from 'redux-persist'
import * as rp from 'redux-persist'
import storage from 'redux-persist/lib/storage'
import hardSet from 'redux-persist/lib/stateReconciler/hardSet'

import createCollectionForm from './slices/CollectionFormSlice'
import auth from './slices/AuthSlice'

const persistConfig = {
  key: 'root',
  storage,
  stateReconciles: hardSet as (inboundState: CombinedState) => CombinedState,
  version: 1,
}

type CombinedState = typeof rootReducer extends Reducer<infer U, any> ? U : never

const rootReducer = combineReducers({
  auth,
  createCollectionForm,
})

const persistedReducer = persistReducer(persistConfig, rootReducer)

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

export const persistor = persistStore(store)


export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

똑같은 설정으로 시도해보니 효과가 있는 것 같았어요.도움이 된다면, 난 할 수 있어."@reduxjs/toolkit": "^1.4.0",,"redux-persist": "^6.0.0",그리고."react-redux": "^7.2.1".HTH.

언급URL : https://stackoverflow.com/questions/63761763/how-to-configure-redux-persist-with-redux-toolkit

반응형