JSON object vs window variable for passing server-side rendered initial state using reactjs

不想你离开。 提交于 2019-12-06 10:14:06

The latter avoids a global variable and the former avoids a DOM lookup. I'd go with the former, just because it requires less code.

One concern is if you have </script in your JSON it could allow injection or accidental error. To prevent this you can replace < with \u003c.

<script>
window.initialState = {{
    JSON.stringify(initialState).replace(/</g, '\\u003c')
}}; 
</script>

I like to create a start function that kicks things off on the server and in the browser. On the browser side I render that initial state object as an argument:

<script type="text/javascript">
    var app = new App();
    document.addEventListener('DOMContentLoaded', function(e) {
        document.removeEventListener('DOMContentLoaded');

        app.start({{JSON.stringify(initialState)}});
    });
</script>

In the start function, I have something like this for the browser:

App.prototype.start = function(initState) {
    React.render(RootComponent(initState), document.getElementById('container'));
}

In this case start() doesn't do much, but in a full implementation I would also handle the server-side rendering here. Most of my ideas for this came from this talk and examples: https://github.com/zertosh/ssr-demo-kit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!