浏览器历史记录需要DOM

时间:2018-02-06 18:24:58

标签: reactjs express create-react-app serverside-rendering

关于此主题已经有一些问题,解决方案指向服务器上的memoryHistory。但是,我这样做了,问题仍然存在于客户端文件夹中的store.js上。虽然我没有使用这个客户端/ store.js,但它仍然给我与主题相同的错误。

所以我的猜测是我在服务器或客户端包装组件的方式有问题。

我正在处理已经加载的项目堆栈 - redux,react-redux,react-router-redux,redux-thunk,history等等...这些对我来说是一个令人生畏的令人生畏的补充SSR的设置 - 服务器端渲染(我的基本动机) 我将分享本练习中涉及的结构和重要文件!

让我们先欢迎服务器。

服务器/ bootstrap.js

require('ignore-styles');
require('babel-register')({
    ignore: [ /(node_modules)/ ],
    presets: ['es2015', 'react-app']
});
require('./index');

服务器/ index.js

import express from 'express';
import serverRenderer from './middleware/renderer';

const PORT = 3000;
const path = require('path');
const app = express();
const router = express.Router();

// root (/) should always serve our server rendered page
router.use('^/$', serverRenderer);
// other static resources should just be served as they are
router.use(express.static(
    path.resolve(__dirname, '..', 'build'),
    { maxAge: '30d' },
));
router.use('*', serverRenderer);
// tell the app to use the above rules
app.use(router);
// start the app
app.listen(PORT, (error) => {
    if (error) {
        return console.log('something bad happened', error);
    }

    console.log("listening on " + PORT + "...");
});

服务器/中间件/ renderer.js

import React from 'react'
import ReactDOMServer from 'react-dom/server';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import store from '../../src/store';
import {createMemoryHistory } from 'history';
import { StaticRouter } from 'react-router'

// import our main App component
import App from '../../src/index';
const path = require("path");
const fs = require("fs");
const history = createMemoryHistory({
  initialEntries: ['/', '/next', '/last'],
  initialIndex: 0
})
export default (req, res, next) => {
    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()
        }
        const html = ReactDOMServer.renderToString(
            <Provider store={store}>
              <ConnectedRouter history={history}>
                <App />
              </ConnectedRouter>
            </Provider>
        );
        return res.send(
            htmlData.replace(
                '<div id="root"></div>',
                `<div id="root">${html}</div>`
            )
        );
    });
}

我的src文件夹结构将是

  • 部件
  • 容器
    • 应用
      • index.js
      • styles.js
  • index.js
  • store.js

的src / index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { StaticRouter } from 'react-router'

import './index.css';
import store, { history } from './store';
import App from './containers/app';

const target = document.querySelector('#root');

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <App />
    </ConnectedRouter>
  </Provider>,
  target
);

难以理解

的src / store.js

import { createStore, applyMiddleware, compose } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import thunk from 'redux-thunk';
import createHistory from 'history/createBrowserHistory';
import rootReducer from './reducers';

export const history = createHistory();

const initialState = {};
const enhancers = [];
const middleware = [thunk, routerMiddleware(history)];

if (process.env.NODE_ENV === 'development') {
  const devToolsExtension = window.devToolsExtension;

  if (typeof devToolsExtension === 'function') {
    enhancers.push(devToolsExtension());
  }
}

const composedEnhancers = compose(applyMiddleware(...middleware), ...enhancers);

const store = createStore(rootReducer, initialState, composedEnhancers);

export default store;

在运行节点服务器/ bootstrap.js上,它给我一个错误 Invariant Violation: Browser history needs a DOM并在store.js中生成此错误

如果有人可以通过代码告诉我,我在SSR的当前create-react-app中分享了我做错的地方和地点!

1 个答案:

答案 0 :(得分:3)

我正在加载应用程序两次。一旦进入客户端和其他服务器。 我在服务器中使用相同的设置(提供者和连接的路由器)进行渲染,并且重要的是将createBrowserHistory更改为createMemoryHistory并且它有效。