在带有SSR的React中未定义窗口

时间:2018-07-26 14:44:39

标签: reactjs react-router

为什么这行:

const store = configureStore(window.INITIAL_STATE);

导致此错误:

ReferenceError: window is not defined

我正在尝试更新一个非常旧的代码库(带有SSR的React 15.2,react-router v.3x)。

问题行下面的代码是

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory} routes={getRoutes(store)}/>
  </Provider>,
  document.getElementById('app')
);

更新: 这是configureStore.js

import { applyMiddleware, compose, createStore } from 'redux';
import thunk from 'redux-thunk';
import promise from 'redux-promise';
import createLogger from 'redux-logger';
import rootReducer from '../reducers'

export default function configureStore(initialState) {
  const logger = createLogger();
  const store = createStore(
    rootReducer,
    initialState,
    applyMiddleware(thunk, promise, logger)
  );

  // this is from webpack 1.x
  // if (module.hot) {
  //   // Enable hot module replacement for reducers
  //   module.hot.accept('../reducers', () => {
  //     const nextRootReducer = require('../reducers');
  //     store.replaceReducer(nextRootReducer);
  //   });
  // }

  return store;
}

如果有帮助

更新2

Router.match({ routes: routes.default(store), location: req.url }, (err, redirectLocation, renderProps) => {
    if (err) {
      res.status(500).send(err.message);
    } else if (redirectLocation) {
      res.status(302).redirect(redirectLocation.pathname + redirectLocation.search);
    } else if (renderProps) {
      var html = ReactDOMServer.renderToString(React.createElement(Provider, { store: store },
        React.createElement(Router.RouterContext, renderProps)
      ));
      res.render('layouts/main', {
        html: html,
        initialState: store.getState()
      });
    } else {
      res.sendStatus(404);
    }
  });
});

1 个答案:

答案 0 :(得分:4)

如果正确执行ssr,则应该有两个不同的入口文件,一个用于客户端(浏览器),一个用于服务器端(nodejs)

对于客户端,此行代码已执行const store = configureStore(window.INITIAL_STATE);

对于服务器端

const initState = getStateSomehow();
const store = configureStore(initState);

当服务器将初始HTML呈现给客户端时,请插入脚本,以便window.INITIAL_STATE具有相同的值

<script>
    window.INITIAL_STATE = ${JSON.stringify(initState).replace(/</g, '\\u003c')}
</script>

我建议阅读更多关于https://redux.js.org/recipes/server-rendering

的信息