Server-side and client-side responses fail

First, the page was displayed by the server, and then on the client / browser side, the Javascript script re-displayed the entire page!
I do not think that it should be so, as this is a very bad user experience.

One thing that I noticed is that the data-reactid my root element displayed by the server has some hash, for example .2t5ll4229s , and all child elements have this as a prefix, for example. .2t5ll4229s.0 (first child). Whereas, on the browser side, data-reactid has .0 for the root element and .0.0 for the first child.
If data-reactid really the culprit here, is there a way to set the selection value for it as eric123 for both the client side and the server.

If data-reactid not the culprit here, how can I make the rendering on the server and client side React seamless, then only some elements should be re-rendered on the client side, and not all !?

My template is index-server-local.html:

 ... <body> <div id="content" class="container-fluid wrapper no-padding-left no-padding-right"> {{{reactHtml}}} </div> <script src="bundle.js"></script> </body> ... 

My server.js:

 server.get('*', function (req, res) { console.log('request url', req.url); log.debug('routes are', JSON.stringify(routes)); res.header("Access-Control-Allow-Origin", "*"); match({routes, location: req.url}, (error, redirectLocation, renderProps) => { if (renderProps) { let htmlStr = React.renderToString(<RoutingContext {...renderProps} />); res.render('index-server-local', { reactHtml: htmlStr }); } } 

My browser.js:

 React.render(<Router history={history} routes={routeConfig} />, document.getElementById('content')); 

I am using response-router 1.0.0 and React 0.13.3.

+7
reactjs react-router express
source share
1 answer

We need to serialize the data (or state) on the server side and send it to the client side for deserialization, otherwise the data on the client side will be different from how the server displays it. it will be rebooted for sure. One exception: a blank static page, in which case React recommends that we use renderToStaticMarkup

Like renderToString, except that it does not create additional DOM attributes, such as data-react-id, which React uses internally. This is useful if you want to use React as a simple static page generator, since removing unnecessary attributes can save a lot of bytes.

So how do we serialize - deserialize? Here is the simple version: in your template index-server-local.html:

  <script src="bundle.js"></script> 

in

  <script dangerouslySetInnerHTML={{{{__html: 'window.__data=' + JSON.stringify({key: 'value'})}}}} /> <script src="bundle.js"></script> 

And on the client side, we can now use __datadata. How to match data with your component of your choice.

I recommend Reudx for this:

  createStore(browserHistory, initialState) 

And then

  <Provider store={store}> { component } </Provider> 
+1
source share

All Articles