Browser history needs a DOM

醉酒当歌 提交于 2019-12-11 04:23:54

问题


There are already questions around this topic with solutions pointing to memoryHistory on server. However, I did that and the problem still remains to be on store.js which is inside client folder. Although I am not using this client/store.js it still gives me same error as the subject.

So my guess is there is something wrong in the way I am wrapping up my component on server or client side.

I am working on already loaded project stack - redux, react-redux, react-router-redux, redux-thunk, history etc... and these are honestly daunting for me to make an addition for a setup for SSR -server side rendering (my basic motive) I will share my structure and important files which are involved in this exercise !

Let's welcome the server first.

server/bootstrap.js

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

server/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 + "...");
});

server/middleware/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>`
            )
        );
    });
}

My src folder structure will be

  • components
  • containers
    • app
      • 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
);

The tough nut to understand

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;

on running node server/bootstrap.js, it give me an error Invariant Violation: Browser history needs a DOM and this error generates in store.js

If someone could please let me know by the code shared what and where I am doing wrong to my current create-react-app for SSR!


回答1:


I was loading the App twice. Once in client and other in server. I rendered in server alone with the same setup (Provider and connected router) and importantly changed the createBrowserHistory to createMemoryHistory and it worked.



来源:https://stackoverflow.com/questions/48649569/browser-history-needs-a-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!