개발
[React]redux 새로고침을 해도 값 유지시키기(state 값 유지시키기)
1223v
2022. 10. 14. 15:11
프로젝트에서 react의 redux를 사용하는데,
새로고침이나 하이퍼링크를 이용한 이동시 state값이 초기화되버린다.
그래서 새로고침해도 state값이 유지되는 redux-persist를 사용하려고 한다.
폴더 구조는 이러하다.
www.npmjs.com/package/redux-persist
redux-persist
persist and rehydrate redux stores. Latest version: 6.0.0, last published: 3 years ago. Start using redux-persist in your project by running `npm i redux-persist`. There are 906 other projects in the npm registry using redux-persist.
www.npmjs.com
1. redux-persist 설치
npm install --save redux-persist
2. src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './components/App';
import {Provider} from 'react-redux'
import { applyMiddleware, createStore ,compose} from 'redux'
import promiseMiddleware from 'redux-promise'
import ReduxThunk from 'redux-thunk';
import persistedReducer from './_reducers'; //추가
import { persistStore } from 'redux-persist'; // 추가
import { PersistGate } from 'redux-persist/integration/react'; // 추가
import {composeWithDevTools} from 'redux-devtools-extension/developmentOnly';
import {BrowserRouter} from 'react-router-dom';
const store = createStore(persistedReducer, compose(
applyMiddleware(promiseMiddleware, ReduxThunk),
//window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
//-- redux 확장프로그램이 깔려있어야 실행가능.
)
)//수정
const persistor = persistStore(store) // 추가
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<Provider
store={store}
>
<PersistGate persistor={persistor}> //추가
<App />
</PersistGate>
</Provider>
</BrowserRouter>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
3.src/_reducers/index.js 수정
import { combineReducers } from 'redux';
import user from './user_reducer';
import { persistReducer } from 'redux-persist'; // 추가
import storage from 'redux-persist/lib/storage'; // 추가
const persistConfig = {
key: 'root',
storage,
} // 추가
const rootReducer = combineReducers({
user,
})
const persistedReducer = persistReducer(persistConfig, rootReducer); // 추가
export default persistedReducer; // 수정
redux-persist는 기본적으로 localstorage 저장하거나 세션에 저장하거나 인데 필자는 로컬스토리지를 선택함.
import storage from 'redux-persist/lib/storage'
src/_reducers/index.js에 넣어준 import가 이거임.
728x90