使用react-router v4和express.js进行服务器渲染 [英] server rendering with react-router v4 and express.js

查看:103
本文介绍了使用react-router v4和express.js进行服务器渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用最新版本的react-router v.4设置服务器端渲染。我按照本教程 https://react-router.now.sh/ServerRouter

I'm trying to set up server-side rendering with the newest version of react-router v.4. I followed this tutorial https://react-router.now.sh/ServerRouter.

刷新浏览器时出现以下错误:不变违规:React.Children.only预计会收到一个React元素子项。

I get following error when I refresh browser: Invariant Violation: React.Children.only expected to receive a single React element child.

我的 routes.jsx 文件:

export default () =>
  <div>
    <Header />
    <Match pattern="/" component={Home} />
    <Match pattern="/about" component={About} />
    <Miss component={NotFound} />
  </div>;

index.jsx 我正在呈现应用

import  BrowserRouter from 'react-router';    
import Routes from './routes';

ReactDOM.render(<BrowserRouter> <Routes /> </BrowserRouter>, document.getElementById('app'));

现在作为服务器,我正在使用 express.js 。这是我的配置:

Now as server I'm using express.js. Here is my configuration:

import  Routes  from '../routes';

server.use((req, res) => {
  const context = createServerRenderContext();
  let markup = renderToString(
    <ServerRouter location={req.url} context={context} > <Routes /> </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}> <Routes /> </ServerRouter>);
    }
    res.write(markup);
    res.end();
  }
});

除了官方版本之外,我没有找到任何使用此版本的react-routes进行服务器渲染的教程。
任何人都可以帮我解决我做错的事吗?谢谢。

I didn't find any tutorial for server-rendering with this version of react-routes except official. Can anyone help me what I'm doing wrong ? thanks.

推荐答案

解决了!

首先问题是我在< Routes /> 标签周围有空格。

First problem was that I had spaces around <Routes /> tag.

正确解决方案:

<ServerRouter location={req.url} context={context}><Routes /></ServerRouter>);

第二个问题包含在< Header /> 标记。

Second problem was in included <Header /> tag in routes.jsx file.

我遇到以下错误(不变违规:元素类型无效:预期字符串(内置)组件)或类/函数(用于复合组件)但得到:undefined。检查 StatelessComponent的渲染方法

I had the following error (Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of StatelessComponent)

文件Header.jsx包含以下代码行:

File Header.jsx contained the following line of code:

import Link  from 'react-router';

正确的解决方案:(我忘了放大括号):

Correct solution: (I forgot to put curly brackets ):

 import { Link } from 'react-router';

这篇关于使用react-router v4和express.js进行服务器渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆