搭建渲染服务器
基于Express 的渲染服务器
renderToString
renderToString
和 renderToStaticMarkup
用来将组件
import ReactDOMServer from "react-dom/server";
var ReactDOMServer = require("react-dom/server");
ReactDOMServer.renderToString(element);
我们可以在服务端即使用renderToString
将组件转化为ReactDOM.render()
渲染某个组件时,如果renderToStaticMarkup
,其很类似于renderToString
,不过其忽略了额外的譬如data-reactid
这样的
服务器端渲染除了要解决对浏览器环境的依赖,还要解决两个问题:
-
前后端可以共享状态
-
前后端路由可以统一处理
状态传递
路由权限控制
import { renderToString } from "react-dom/server";
import { match, RouterContext } from "react-router";
import routes from "./routes";
serve((req, res) => {
// Note that req.url here should be the full URL path from
// the original request, including the query string.
match(
{ routes, location: req.url },
(error, redirectLocation, renderProps) => {
if (error) {
res.status(500).send(error.message);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
// You can also check renderProps.components or renderProps.routes for
// your "not found" component or route respectively, and send a 404 as
// below, if you're using a catch-all route.
res
.status(200)
.send(renderToString(<RouterContext {...renderProps} />));
} else {
res.status(404).send("Not found");
}
}
);
});