Is the .__ INITIAL_STATE__ window another preferred way to pass initial state to the client in React Universal applications?

I am currently reading a book about React and Universal applications, in which the author claims that it is best to use the initial state from server to client:

server.js

import React from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import Myapp from '../MyApp';
import api from '../services';

function renderPage(html, initialData) {
    return `
        <html>
            <body>
                ${html}
            </body>
            <script>
                window.__INITIAL_STATE__ = ${JSON.stringify(initialData)};
            </script>
            <script src="bundle.js"></script>
        </html>
    `;
}

export default function(request, reply) {
    const initialData = api.getData();
    const html = renderToStaticMarkup(<MyApp />);
    reply(renderPage(html, initialData);
}

And then, in the client, you will read the data as follows:

bundle.js

const initialData = window.__INITIAL_STATE__ || {};
const mountNode = document.getElementById('root');
ReactDOM.render(<MyApp />, mountNode);

As I understand it, the initial state is first converted to a string, and then attached as a global object to the window object.

This decision looks very rude to me. The book was released in mid-2016. Is there a window.__INITIAL_STATE__way to do this, or are there better solutions?

, , , , , , , .

+4
2

HTTP , , , , , , . , , , , .

, , , , , .

, 1, , , , .

0

: .

, , XSS, JSON.stringify(initialData), , :

import serialize from 'serialize-javascript';

 window.__INITIAL_STATE__ = ${serialize(initialData)};
0

Source: https://habr.com/ru/post/1676158/


All Articles