Answer the question
In order to leave comments, you need to log in
How to render a React application on the server after the data is loaded?
Hello!
Faced such a problem.
There is a React application that is rendered both on the server and on the client.
But some components in componentWillMount make a request to the api to get data, and in this regard, express.js sends a page to the client that was poisoned by components without data.
What is the best way to build an application architecture so that an application is rendered on the server with data received asynchronously?
For routing I use react-router-component
Answer the question
In order to leave comments, you need to log in
First, divide your components into smart and dumb - https://medium.com/@dan_abramov/smart-and-dumb-com... .
Thus, your route handlers should be predominantly smart. In each smart component that needs data for rendering, you can make a fetchComponentData method (asynchronous requests will be executed in it).
Next, take react router version 1.0.0 (currently 1.0.0-rc1 is relevant) and directly in the documentation it is told how to make a rendering server. renderProps has a list of route handler components - you can loop through them and call the aforementioned fetchComponentData function:
match({ routes, location }, (error, redirectLocation, renderProps) => {
if (redirectLocation)
res.redirect(301, redirectLocation.pathname + redirectLocation.search)
else if (error)
res.send(500, error.message)
else if (renderProps == null)
res.send(404, 'Not found')
else {
const promises = _.map(
_.filter(renderProps.components, component => component.fetchComponentData),
component => component.fetchComponentData(/*тут можно передать данные роута*/)
);
Promises.all(promises).then(() => res.send(renderToString(<RoutingContext {...renderProps}/>)));
}
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question