【问题标题】:Isomorphically render html string with Koa用 Koa 同构渲染 html 字符串
【发布时间】:2015-08-13 17:27:35
【问题描述】:

我正在尝试让 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>
)

ma​​in.js

import React from "react"

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

export default Main

遇到几个错误:

警告:Component(...): No render 在返回的方法中找到 组件实例:您可能忘记在您的 组件,或者您可能不小心尝试渲染元素 其类型是不是 React 组件的函数。

警告:不要设置 React 元素的 props 属性。反而, 在最初创建元素时指定正确的值。

TypeError: 无法添加属性上下文,对象不可扩展

警告:有些东西正在直接调用 React 组件。用一个 工厂或 JSX 代替。见:https://fb.me/react-legacyfactory

【问题讨论】:

  • 当你this.body = string时会发生什么?
  • 我只是在正文中得到一个Not Found。
  • 设置错误处理程序并找出导致错误的原因。 github.com/koajs/koa/wiki/Error-Handling
  • 添加了错误处理,并尝试修复Something is calling a React component directly,但仍然出现很多错误

标签: rendering reactjs ecmascript-6 koa isomorphic-javascript


【解决方案1】:

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

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;

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

【讨论】:

    【解决方案2】:

    我也收到了“直接调用 React 组件”的警告,并通过产生一个承诺来修复它

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

    【讨论】:

      猜你喜欢
      • 2018-01-20
      • 2014-08-29
      • 2021-01-30
      • 2015-06-27
      • 2011-07-26
      • 2016-11-13
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      相关资源
      最近更新 更多