【问题标题】:Isomorphic React.js & iso-http同构 React.js 和 iso-http
【发布时间】:2015-04-21 03:57:12
【问题描述】:

我正在构建一个 React Web 应用程序,我想同时呈现服务器端和客户端。我一直在使用isomorphic-react-template,但我使用iso-http 来查询我的内容服务器。我的目标是让应用程序在服务器端直接查询内容服务器并将内容呈现为 HTML 时;并让应用在客户端执行正常的 AJAX 内容请求时。

这是我正在使用的代码。它在浏览器上运行良好,但服务器端渲染不包含数据;我推测是因为服务器端渲染在编译 HTML 并将其发送过去之前没有等待异步 http 调用返回:

componentDidMount: function() {
  var id = this.getParams().id;
  var classThis = this;

  request
  .get("http://content.example.com/things/" + id)
  .end(function(response) {
    response.body = JSON.parse(response.text);
    if (response.ok) {
      classThis.setState({ data: response.body });
    } else {
      classThis.setState({ data: null });
    }
  });
}

我知道这都是相当新的东西;但是有没有一种已知的方法来解决这个问题,以便服务器端渲染器在发送之前等待某些异步调用完成?

【问题讨论】:

  • componentDidMount 永远不会在服务器上运行。您必须使用手头的数据(而不是请求它)呈现到字符串。
  • 那么有没有一种“最佳实践”方式在服务器和浏览器上运行不同的代码?我可以抽象出数据检索函数,然后从浏览器上的componentDidMount 和服务器上的getInitialState 调用它。看起来有点笨拙,但我准备接受它的必要性。
  • 看来我在问这个问题:github.com/reactjs/react-page/issues/47

标签: javascript reactjs


【解决方案1】:

我已经设法与react-async 一起工作。

我已经像这样提取了我的异步函数,因此我可以从componentDidMountReactAsync 使用的异步 getInitialStateAsync 函数调用它:

mixins: [ ReactAsync.Mixin ],

getInitialStateAsync: function(callback) {
  this.getContent(function(state) {
    callback(null, state)
  }.bind(this))
},

componentDidMount: function() {
  this.getContent(function(state) {
    this.setState(state);
  }.bind(this));
},

getContent: function(callback) {
  var id = this.getParams().id;
  request
    .get("http://content.example.com/things/" + id)
    .end(function(response) {
      response.body = JSON.parse(response.text);
      if (response.ok) {
        callback({ error: {}, post: response.body })
      } else {
        callback({ post: {}, error: response.body });
      }
    });
}

然后在我的server.jsx 中使用异步函数进行渲染:

ReactAsync.renderToStringAsync(<Handler />, function(err, markup) {
  var html   = React.renderToStaticMarkup(<Html title={title} markup={markup} />);
  res.send('<!DOCTYPE html>' + html);
});

显然这里有很大的潜力(如果服务器不存在,整个页面将无法呈现),但这感觉就像是正确方法的开始!

【讨论】:

    猜你喜欢
    • 2016-08-17
    • 2018-11-24
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多