react server rendering 是指渲染到哪种程度?

2015-12-27 12:36:15 +08:00
 plantain

比如这个例子:

let initialState = {
  books: null,
  readers: null
};
let TestComponent = React.createClass({
  getInitialState: function() {
    return initialState;
  }
  componentDidMount: function() {
    $.get("/api/books").then(/*这里设置 state: books*/);
    $.get("/api/readers").then(/*这里设置 state: readers*/);
  }
});
  1. 后端通过“函数调用”的方式分别获取到 books 和 readers ,赋给 initialState 后 renderToString ,再通过模板嵌入到 html 中,前端选择性执行 componentDidMount 里的代码(如果已有数据就不该执行,如果从别的页面路由过来,则需要执行);
  2. 后端通过“ restful api 调用”的方式,其它和 1 一样;
  3. 后端并不获取 books 和 readers ,也不改变 initialState ,直接 renderToString ,再通过模板嵌入到 html 中,前端不改变 componentDidMount ,前端会在加载后加载数据。

因为 react 的 checksum 是根据 initialState 来计算的,所以第 1 、 2 种方式中修改 initialState 后,会引起 checksum 不一致,错误类似于这样:

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:

所以好像是行不通的。

我的问题是,像 1 、 2 这种程度(会加载数据)的方法是怎么实现的?还是说 react server rendering 就是指像 3 这样(不会加载数据)?

比如这个帖子( https://www.v2ex.com/t/203001 )说的好像是“会加载数据”的哪种。

1071 次点击
所在节点    问与答
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/246427

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX