gpt4 book ai didi

javascript - 尽管所有反应路由器版本冲突,如何在 react 中进行服务器端渲染?

转载 作者:搜寻专家 更新时间:2023-10-31 22:53:17 24 4
gpt4 key购买 nike

我正在尝试使用 react 和 react-router-dom 进行服务器端渲染我之前已经这样做过,但是对于新版本,它会抛出一个错误你不应该在路由器之外使用 Switch 我认为这是版本冲突,但是否有解决方案(react-router-config - You should not use outside a (it is inside a Router!))。

服务器.js

import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from '../client/src/AppRoutes';
import { StaticRouter } from 'react-router-dom';
import { renderRoutes } from 'react-router-config'


const app = express();



app.get('*', (req, res) => {
const routerContext = {};
res.send(`
<!doctype html>
<html lang="en">
<head>SSR</head>
<body>
<div id="root">${ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={routerContext}>
<div>{renderRoutes(App)}</div>
</StaticRouter>
)}</div>
<!-- <script src="/dist/main.js"></script>-->
</body>
</html>
`);
});


app.listen(3000, (error) => {
if (error) {
return console.log('something bad happened', error);
}
console.log("listening on " + 3000 + "...");
});

AppRoutes.js

import PageA from './Container/PageA';
import PageB from './Container/PageB';
import Home from './Container/Home'
import MainPage from './Container/MainPage';



export default [
{
...MainPage,
routes:[
{
...Home,
path:'/',
exact:true
},
{
...PageA,
path:'/a',
exact:true
},
{
...PageB,
path:'/b',
exact:true

}
]
}
]

包.json

{
"name": "reactSSRwithCodeSplitting",
"version": "1.0.0",
"description": "",
"main": "server/server.js",
"scripts": {
"test": "babel-node server/index.js",
"start": "nodemon server/index.js",
"build": "babel server --out-dir ./dist --source-maps",
"serve": "node ./dist/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-loadable": "^5.5.0",
"react-router-config": "^5.0.1",
"react-router-dom": "^5.0.1"
},
"devDependencies": {
"@babel/cli": "^7.5.5",
"@babel/core": "^7.5.5",
"@babel/node": "^7.5.5",
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
"@babel/preset-env": "^7.5.5",
"@babel/preset-react": "*",
"@babel/register": "^7.5.5",
"chai": "^4.2.0",
"nodemon": "^1.19.1"
}
}

最佳答案

快速修复:

  1. 删除您的node_modules
  2. "react-router": "^5.0.1" 添加到您的 package.json
  3. 使用 npm install 重新安装。

确保 react-router, react-router-config, react-router-dom 是同一个版本。

怎么了?

当我尝试重现你的错误时,我发现问题中你的 package.json 缺少 react-router 依赖,这让我无法启动服务器。

从你的故事来看,我猜你的 node_modules 中有另一个版本的 react-router,它与 react-router- 不同步配置react-router-dom 版本 5.0.1。

所以我尝试重现这个问题:

"react-router": "^4.3.0",
"react-router-config": "^5.0.1",
"react-router-dom": "^5.0.1"

这将导致您提到的问题。

关于javascript - 尽管所有反应路由器版本冲突,如何在 react 中进行服务器端渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57447677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com