【问题标题】:How to solve redux-persist failed to create sync storage. falling back to noop storage in React.js如何解决 redux-persist 创建同步存储失败。回退到 React.js 中的 noop 存储
【发布时间】:2020-12-13 12:35:32
【问题描述】:

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

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

我该如何解决这个问题? Server.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}`);
});

【问题讨论】:

    标签: reactjs express redux server-side-rendering redux-saga


    【解决方案1】:

    我可能会很晚才回答,但是,

    在 NextJs 的情况下,问题是通过有条件地使用存储来解决的,它是 client sideserver side 用于持久化状态。 至于事实上'window is not defined on server side'.

    示例代码:

    const isClient = typeof window !== "undefined";
    
    let mainReducer;
    if (isClient) {
     const { persistReducer } = require("redux-persist");
     const storage = require("redux-persist/lib/storage").default;
    
     const rootPersistConfig = {
       key: "root",
       storage: storage,
       blacklist: ["countries"],
     };
    
     const countriesPersistConfig = {
       key: "countries",
       storage: storage,
       whitelist: ["countriesList"],
     };
    
     /* COMBINE REDUCERS */
     const combinedReducers = combineReducers({
       countries: persistReducer(countriesPersistConfig, countries),
     });
    
     mainReducer = persistReducer(rootPersistConfig, combinedReducers);
    } else {
     mainReducer = combineReducers({
       countries,
     });
    }
    

    如果仍然不能解决问题。尝试阅读此线程 - using-redux-with-redux-persist-with-server-side-rendering

    谢谢。

    【讨论】:

      猜你喜欢
      • 2020-01-06
      • 2021-08-15
      • 2021-08-29
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 2018-02-26
      相关资源
      最近更新 更多