使用react-router 4的服务器端重新编译工作

时间:2017-06-20 18:14:18

标签: reactjs express serverside-javascript react-router-v4

我正在尝试使用react-router 4进行服务器端渲染,但是当我重新加载不同于'/'的URL的页面时,我收到此错误:

TypeError: (0 , _reactRouter.createServerRenderContext) is not a function

我的服务器文件是:

import express from 'express';
import React from 'react';
import expressStaticGzip from 'express-static-gzip';
import { renderToString } from 'react-dom/server';
import { ServerRouter, createServerRenderContext } from 'react-router';
import App from './app/components/App';

const app = express();

app.use('/', expressStaticGzip('dist'));

app.use((req, res) => {
  const context = createServerRenderContext();
  let markup = renderToString(
    <ServerRouter location={req.url} context={context} > <App /> </ServerRouter>);
  const result = context.getResult();

  if (result.redirect) {
    res.writeHead(301, {
      Location: result.redirect.pathname,
    });
    res.end();
  } else {
    if (result.missed) {
      res.writeHead(404);
      markup = renderToString(
        <ServerRouter location={req.url} context={context}> <App /> </ServerRouter>);
    }
    res.write(markup);
    res.end();
  }
});

app.listen(process.env.PORT || 3000, () => {
  console.info(`Listening port ${process.env.PORT || 3000}`);
});

我的组件是:

const App = () => (
  <div>
    <Header />
    <Main />
  </div>
);



const Main = () => (
  <main>
    <Switch>
      <Route exact path="/" component={Dashboard} />
      <Route path="/attendance" component={Attendance} />
    </Switch>
  </main>
);

const Header = () => (
  <header>
    <nav>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/attendance">Attendance</Link></li>
      </ul>
    </nav>
  </header>
);

我是react-router 4的新手,我不知道如何解决这个问题。

任何人都可以帮我吗?

提前致谢。

0 个答案:

没有答案