如何在nextjs13中配置和持久化redux工具包

sulc1iza  于 2023-04-06  发布在  其他
关注(0)|答案(1)|浏览(209)

我在使用reduxjs工具包将redux持久化到nextjs 13时遇到了问题。根据nextjs控制台,我下面使用的代码无法构建同步存储。恢复到noop存储。有人能帮助我如何使用nextjs和reduxjs工具包持久化redux吗?
下面是实际的控制台消息错误:redux-persist无法创建同步存储。正在回退到noop存储
以下是我所做的:
我的store.js里有这个

import { configureStore } from "@reduxjs/toolkit";
import authenticateSlice from "./slices/authenticateSlice";
import { persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import { encryptTransform } from "redux-persist-transform-encrypt";
import { combineReducers } from "redux";
import thunk from "redux-thunk";

const reducers = combineReducers({
  auth: authenticateSlice.reducer,
});

let transforms = null;

if (process.env.NODE_ENV === "production") {
  const encrypt = encryptTransform({
    secretKey: process.env.NEXT_PUBLIC_REDUX_SECRET,
    onError: function (error) {
      // Handle the error.
    },
  });
  transforms = [encrypt];
}

const persistConfig = {
  key: "root",
  storage,
  transforms,
};

const persistedReducer = persistReducer(persistConfig, reducers);

const store = configureStore({
  reducer: persistedReducer,
  middleware: [thunk],
});

export default store;

然后我把它 Package 在我的_app.js中,因为我使用的是nextjs 13:

import "@/styles/globals.css";
import Head from "next/head";
import Template from "template/index";
import React from "react";
import store from "next-redux/store";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import { persistStore } from "redux-persist";
import LinearProgress from "@mui/material/LinearProgress";
import ReactDOM from "react-dom";

let persistor = persistStore(store);

const App = ({ Component, pageProps }) => {
  return (
    <>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <Provider store={store}>
        <PersistGate persistor={persistor} loading={<LinearProgress />}>
          <Template>
            <Component {...pageProps} />
          </Template>
        </PersistGate>
      </Provider>
    </>
  );
};

export default React.memo(App);
fae0ux8s

fae0ux8s1#

由于您正在使用v6redux-persist,因此需要执行以下操作:
首先添加AsyncStorage包如下:

yarn add @react-native-async-storage/async-storage

然后,

import AsyncStorage from '@react-native-async-storage/async-storage';
const persistConfig = {
  //...
  storage: AsyncStorage,
}

请不要忘记删除下面的行

import storage from "redux-persist/lib/storage";

参考链接-Release notes for Redux-Persist v6

更新

我猜你所面临的错误是因为你不能在Node.js中创建本地存储。

import createWebStorage from "redux-persist/lib/storage/createWebStorage";

并添加检查,如下所示:

const storage = typeof window !== "undefined" ? createWebStorage("local") : createNoopStorage();

在这里你会发现详细的解释。

相关问题