使用 Meteor
react-router-ssr
构建同构 react
render() {
return (
<li>
<h3>
<Link to={`/post/${this.props._id}`}>{this.props.title}</Link>
<small>{this.props.author}</small>
{/* 注意这里的时间格式化 */}
<small>{new Date(this.props.createAt).toLocaleDateString()}</small>
</h3>
</li>
)
}
前台浏览器 给出的是 2015/12/11
后台服务器 给出的是 Friday, December 11, 2015
这样react 就会提示
Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
(client) G9PCSif8CbL9Gi.0.4">2015/12/11</small></
(server) G9PCSif8CbL9Gi.0.4">Friday, December 11,
说两端渲染内容不一致,会丢失服务端渲染的内容
我有一个hack
方法就是使用 componentDidMout
来避免这个提示
但是这样时间并不能第一时间显示,会等到渲染完成后才出来.
请问怎么避免这类同构问题?
前段时间正好在做React同构相关的项目,分享一些经验给题主,其实同构要解决的核心问题就是:
前后端路由统一的处理
前后端数据同步
题主这边要解决的是第二个问题,其实这个问题无论是成熟的iso库还是自己实现,思路都是同一个,那就是:后端进行渲染的时候,将数据同步到前端,最简单暴力的方式是直接置入window.YOURDATA
前端代码
后端代码
这里我选取获取首页的控制器
同构部分的中间件代码逻辑
课外资料
这里还有一些补充资料可能对你有启发:
《React Server Side Rendering 解决 SPA 应用的 SEO 问题》
《React服务端渲染小结》