V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
plantain
V2EX  ›  问与答

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

  •  
  •   plantain · 2015-12-27 12:36:15 +08:00 · 1069 次点击
    这是一个创建于 3058 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如这个例子:

    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 )说的好像是“会加载数据”的哪种。

    第 1 条附言  ·  2015-12-27 13:55:14 +08:00
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   965 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 20:49 · PVG 04:49 · LAX 13:49 · JFK 16:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.