首页 > 解决方案 > 不变违规:浏览器历史记录需要一个 DOM

问题描述

对于服务器端,BrowserRouter 将不起作用,因此将按照文档使用 StaticRouter 。我也在做同样的事情,但我仍然收到错误消息。以下是我的设置

不变违规:浏览器历史记录需要一个 DOM

import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { StaticRouter as Router } from 'react-router';

// import our main App component
import App from '../src/App';

const path = require('path');
const fs = require('fs');

export default (req, res) => {
  // get the html file created by CRA's build tool

  console.log('url : ', req.baseUrl);


  const filePath = path.resolve(__dirname, '..', '..', 'build', 'index.html');

  fs.readFile(filePath, 'utf8', (err, htmlData) => {
    if (err) {
      console.error('err', err);
      return res.status(404).end();
    }

    // render the app as a string
    const html = ReactDOMServer
      .renderToString(<Router location={req.baseUrl}>
        <App />
                      </Router>);

    // now inject the rendered app into our html and send it
    return res.send(htmlData
      .replace('<div id="root"></div>', `<div id="root">${html}</div>`));
  });
};

标签: reactjsreact-routerserver-side-rendering

解决方案


推荐阅读