reactjs - 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>
解决方案
我建议你改变方法并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
推荐阅读
- javascript - 检查对象大小/ BootstrapVue 的长度
- wordpress - TypeScript 导入 block.json - Wordpress Gutenberg
- terraform - 错误:主机无效。解析“https://identity.us-ashburn-1\r.oraclecloud.com”:net/url:URL 中的控制字符无效
- api-platform.com - 在 api-platform 中为不同的方法使用不同的序列化组
- python - Instagram 关注 Selenium Python
- python - Django 如何将数据从 DB 带入 url?
- typescript - 如何使用模板文字类型项生成数组
- c++ - C++ 使用构造函数同时创建带有数组的对象
- google-apps-script - 如何将变量/字符串从按钮传递到 appscript 函数
- mysql - Oracle/SQL/My-Sql 查询中的自定义列?