如何解决如何解决redux-persist无法创建同步存储在React.js中退回到noop存储
我的React Application在客户端渲染中工作正常。我正在尝试出于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}`);
});
解决方法
我可能会很晚才回答,
在 NextJs 的情况下,问题是通过使用基于客户端或服务器端来持久化状态的存储来解决的。 至于事实上'窗口未在服务器端定义'。
示例代码:
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",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
谢谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。