使用 Koa 同构渲染 html 字符串

Isomorphically render html string with Koa

我正在尝试让 Koa 同构渲染它从 react-router 接收到的 html 字符串。

这是我一直在尝试使用的代码:

server.js

import koa from 'koa';
import React from "react";
import Router from "react-router";
import routes from "./routes";
const server = koa();
const port = process.env.NODE_ENV || 8000;

server.use(function *() {
    try {
        yield Router.run(routes, this.request.url, function (Handler) {
            var content = React.renderToString(<Handler/>)
            this.body = content
        })
    }
    catch (err) {
        this.status = err.status || 500;
        this.body = err.message;
        this.app.emit('error', err, this);
    }
 })

server.listen(port, function(err) {
  if (err) throw err;
  console.log("Server running on: http://localhost:"+port)
})

routes.js

import React from "react"
import {Route, DefaultRoute} from "react-router"
import Main from "./components/main"


export default (
  <Route path="/">
    <DefaultRoute handler={Main} name="main" />
  </Route>
)

main.js

import React from "react"

const Main = React.createFactory(React.createClass ({
  render () {
    return (
      <div>HELLO</div>
    )
  }
}))

export default Main

出现几个错误:

Warning: Component(...): No render method found on the returned component instance: you may have forgotten to define render in your component or you may have accidentally tried to render an element whose type is a function that isn't a React component.

Warning: Don't set the props property of the React element. Instead, specify the correct value when initially creating the element.

TypeError: Can't add property context, object is not extensible

Warning: Something is calling a React component directly. Use a factory or JSX instead. See: https://fb.me/react-legacyfactory

我也收到了 "calling a React component directly" 警告并通过 yield a promise 修复了它

function *() {
    this.body = yield new Promise(resolve => {
        Router.run(routes, this.req.url, Handler => {
            resolve(React.renderToString(<Handler/>));
        });
    });
}

对于那些需要回答的人,希望这对你们有所帮助。

server.js

import koa from 'koa';
import React from "react";
import Router from "react-router";
import routes from "./routes";
const server = koa();

let handler;

server.use(function *(next) {
  Router.run(routes, this.request.url, (Handler) => {
    handler = React.renderToString(<Handler/>);
  });
  yield next;
});

server.use(function *() {
  this.body = handler;
});

export default server;

components/index.js

import React from "react";

const Main = React.createClass ({
  render () {
    return (
      <div>HELLO</div>
    );
  }
});

export default Main;

我认为不需要为此创建工厂。