Next.js 项目正在使用 Next-redux-wrapper 和 redux-persist。我以为我应用了redux-persist,但是有一个问题是状态没有保持,并且在刷新期间消失了。
下面是代码 _app.tsx 和 redox/index.tsx。
// _app.tsx
import '../styles/globals.css';
import type { AppProps } from 'next/app';
import styled, { ThemeProvider } from 'styled-components';
import Head from 'next/head';
import { wrapper } from '../redux';
import { createStore } from 'redux';
import { persistStore } from 'redux-persist';
import { PersistGate } from 'redux-persist/integration/react';
import { persistedReducer } from '../redux';
import { DefaultSeo } from 'next-seo';
import { Provider, useStore } from 'react-redux';
const AppSection = styled.section`
display: flex;
flex-direction: column;
justify-content: flex-start;
width: 100vw;
height: 100vh;
`;
function MyApp({ Component, pageProps }: AppProps) {
const store: any = createStore(persistedReducer);
const persistor = persistStore(store);
return (
<PersistGate persistor={persistor} loading={<>loading...</>}>
<AppSection>
<Head>
<title>Lost Gold |</title>
<meta name='description' content='Generated by create next app' />
<link rel='icon' href='/favicon.ico' />
</Head>
<DefaultSeo
title='Lost Gold'
description='당신의 한달 골드량을 한눈에 확인시켜드립니다'
canonical='https://lostgold.vercel.app/'
openGraph={{
type: 'website',
url: 'https://lostgold.vercel.app/',
title: '간편한 골드 계산기, Lost Gold',
description: '당신의 한달 골드량을 한눈에 확인시켜드립니다',
images: [{ url: 'https://lostgold.vercel.app/images/seo_bg.png' }],
site_name: 'Lost Gold',
}}
/>
<Component {...pageProps} />
</AppSection>
</PersistGate>
);
}
export default wrapper.withRedux(MyApp);
redux/index.tsx
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { HYDRATE, createWrapper } from 'next-redux-wrapper';
import { persistReducer, PersistConfig } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import user from './modules/user';
const rootReducer = combineReducers({
user,
});
// hydrate는 여러개 생성되는 스토어를 하나로 묶어줍니다
const reducer = (state: any, action: any) => {
if (action.type === HYDRATE) {
const nextState = {
...state,
...action.payload,
};
return nextState;
}
return rootReducer(state, action);
};
export type RootState = ReturnType<typeof rootReducer>;
const persistConfig = {
key: 'root',
storage,
whitelist: ['user'],
};
export const persistedReducer = persistReducer(persistConfig, rootReducer);
const bindMiddleware = (middleware: any) => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension');
return composeWithDevTools(applyMiddleware(...middleware));
}
return applyMiddleware(...middleware);
};
const store = createStore(reducer, bindMiddleware([]));
const initStore = () => {
return store;
};
export const wrapper = createWrapper(initStore);
这是第一个问题,所以问题可能有很多错误。请给我一些建议。