首页 > 解决方案 > How to initial window.__INITIAL_STATE__ to data in a .ejs view file?

问题描述

I am trying to pass data to client-side by initializing window.INITIAL_STATE, however, this keeps giving me the "Expression expected" error which I am not sure how to fix

    <script>
       window.__INITIAL_STATE__ = <%- JSON.stringify(initialState) %>;
    </script> 

标签: reactjsserverclientejsserver-side-rendering

解决方案


我建议你改变方法并JSON.stringify投入

<script id="__INITIAL_STATE__" type="application/json"> 
    {JSON.stringify(data).replace(/</g,'\\u003c')}
</script>

在客户端就做

const state = JSON.parse(document.getElementById('__INITIAL_STATE__').textContent)

根据 chrome 开发人员的说法,它是更快的解决方案,您不会得到与报价相关的任何惊喜。

使用 JSON.parse 更快的应用程序(Chrome 开发者峰会 2019):https ://www.youtube.com/watch?v=ff4fgQxPaO0


推荐阅读