如何解决redux-persist创建同步存储失败的问题。回到 React.js 中的 noop 存储

Roh*_*utt 3 express reactjs redux server-side-rendering redux-saga

我的 React 应用程序在客户端渲染中运行良好。出于 SEO 目的,我正在尝试在我的应用程序中实现服务器端渲染。

当我运行 server.js 文件时出现错误。

我该如何解决这个问题? 服务器.js

    import path from 'path';
import fs from 'fs';

const PORT = 8080;
const app = express();

const router = express.Router();
app.use(express.json());

const serverRenderer = (req, res, next) => {
    const content = ReactDOMServer.renderToString(
<Provider store={store}>
<PresistGate presist={presist}>
        <StaticRouter location={req.url} context={{}}>
            <App />
        </StaticRouter>
</PresistGate >
</Provider>
    );
    fs.readFile(path.resolve('../dist/index.html'), 'utf8', (err, data) => {
        if (err) {
            console.error(err);
            return res.status(500).send('An error occurred');
        }
        return res.send(data.replace('<div id="root"></div>', `<div id="root">${content}</div>`));
    });
};
router.use('*', serverRenderer);

router.use(express.static(path.resolve(__dirname, '..', 'dist'), { maxAge: '30d' }));

// tell the app to use the above rules
app.use(router);

// app.use(express.static('./build'))
app.listen(PORT, () => {
    console.log(`SSR running on port ${PORT}`);
});
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Siu*_*cio 5

发生该错误是因为您想在服务器端创建 localstorage 对象,所以这就是警告的原因。

我做了以下事情来解决。

import createWebStorage from 'redux-persist/lib/storage/createWebStorage';
const createNoopStorage = () => {
   return {
      getItem(_key: any) {
         return Promise.resolve(null);
      },
      setItem(_key: any, value: any) {
         return Promise.resolve(value);
      },
      removeItem(_key: any) {
         return Promise.resolve();
      },
   };
};
const storage = typeof window !== 'undefined' ? createWebStorage('local') : createNoopStorage();


const reducers = combineReducers({
   YourReducers:xxxx.reducer
 });

const persistConfig = {
   key: 'root',
   storage //here we will put the storage variable that we created above
};
.... and here all the rest of your configuration...

Run Code Online (Sandbox Code Playgroud)