我正在尝试让 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 definerender
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
最佳答案
对于那些需要这个答案的人,希望这会对你们有所帮助。
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;
组件/index.js
import React from "react";
const Main = React.createClass ({
render () {
return (
<div>HELLO</div>
);
}
});
export default Main;
我认为没有必要为此创建工厂。
关于rendering - 使用 Koa 同构渲染 html 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30553421/