如何在服务器上呈现异步初始化的组件

eli*_*erg 19 javascript reactjs

我对ReactJS比较陌生,并且很容易被实现服务器端渲染以减少"第一次推文的时间".我正在运行一个Node-Express-React堆栈,它使用React的renderComponentToString在服务器上预渲染标记.

当组件可以同步呈现时它工作正常,但是在实现ajax填充的组件时我很挣扎(但这适用于组件初始化期间的任何异步操作,例如websocket).

以React网站为例:http://facebook.github.io/react/tips/initial-ajax.html

componentDidMount: function() {
 $.get(this.props.source, function(result) {
  var lastGist = result[0];
  this.setState({
    username: lastGist.user.login,
    lastGistUrl: lastGist.html_url
  });
}.bind(this));
Run Code Online (Sandbox Code Playgroud)

它不能在服务器上运行,因为在使用renderComponentToString时从不触发componentDidMount.通过在客户端和服务器上使用相同的HTTP请求包装器(而不是使用jQuery的$ .get),并在实例化组件并将其作为prop传递之前预先获取数据,可以解决这个简单的情况.

但是,在实际的,复杂的应用程序中,异步依赖可能变得非常复杂,并且预取并不真正适合构建React结构的后代方法.如何在React中实现异步初始化模式,可以在服务器上呈现而不实际安装任何东西(即没有DOM模拟和PhantomJS,这是使用renderComponentToString的全部意义)?

Sop*_*ert 5

我相信最实用的方法是为预加载的数据创建一个可选的 prop,如下所示:

getInitialState: function() {
    if (this.props.initialLastGist) {
        var lastGist = this.props.initialLastGist;
        return {
            username: lastGist.user.login,
            lastGistUrl: lastGist.html_url
        };
    } else {
        return {};
    }
},

componentDidMount: function() {
    if (!this.props.initialLastGist) {
        $.get(this.props.source, function(result) {
            var lastGist = result[0];
            this.setState({
                username: lastGist.user.login,
                lastGistUrl: lastGist.html_url
            });
        }.bind(this));
    }
},
Run Code Online (Sandbox Code Playgroud)

通过这样的设置,如果预加载的数据存在,则可以立即渲染组件;否则,AJAX 请求将在挂载时发送。

目前,服务器渲染始终是同步的,并且componentDidMount不会在服务器上调用,因为它通常涉及 DOM 操作。抱歉,我现在没有更好的解决方案,但一般来说,您希望最大限度地减少对服务器的 HTTP 请求数量,因此值得仔细考虑您的架构,以便您可以收集服务器上所需的所有数据。