简体   繁体   中英

Isomorphic React.js & iso-http

I'm building a react web application which I'd like to render both server side and client side. I've been working off isomorphic-react-template but I've used iso-http to make a query to my content server. My aim is to have the app when server-side query the content server directly and render the content to HTML; and to have the app when client-side to do a normal AJAX request for content.

Here's the code I'm using. It works great on the browser, but the server-side render doesn't include the data; I presume because the server-side render isn't waiting for the async http call to return before it compiles the HTML and sends it over:

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 });
    }
  });
}

I know this is all fairly new stuff; but is there a known way to solve this problem, so that the server side renderer waits for certain async calls to complete before sending?

I've managed to get this working with react-async .

I've pulled out my async function like this so I can call it from componentDidMount and from the asynchronous getInitialStateAsync function that ReactAsync uses:

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 });
      }
    });
}

Then in my server.jsx I'm rendering with the async functions:

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

Obviously there is huge potential for cock up here (the whole page fails to render if the server isn't present) but this feels like the start of the right approach!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM