我正在尝试使用同构服务器端渲染反应构建一个项目。由于某种原因,添加路由后项目停止启动。浏览器抛出以下错误:
错误:不变量失败:浏览器历史记录需要 DOM
也许有人可以告诉我那里出了什么问题。
这是 server.js 代码:
import express from "express";
import path from "path";
import React from "react";
import { StaticRouter } from "react-router";
import ReactDOMServer from "react-dom/server";
import App from "./src/App";
const app = express();
app.get('*', (req,res) => {
const context = {};
const data = ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={context}>
<App />
</StaticRouter>
);
const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="root">${data}</div>
<script src="bundle.js"></script>
</body>
</html>
`;
res.send(html);
});
app.use( express.static( path.resolve( __dirname, "dist" ) ) );
app.listen(3000);
App.jsx 代码:
import React, { Component } from 'react';
import { BrowserRouter, Switch, Route } from "react-router-dom";
import First from './First';
import Second from './Second';
import Home from './Home';
class App extends Component {
render() {
return (
<div>
<BrowserRouter>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/first" component={First} />
<Route path="/second" component={Second} />
</Switch>
</BrowserRouter>
</div>
);
}
}
export default App;
有很多代码和文件可以把它全部带到这里,但我把它放在 Github 存储库中。感谢有人可以提供帮助!
这是存储库的链接: isomorphic-react