简体   繁体   English

无法在React中访问窗口变量

[英]Cannot access window variables in React

I am working on a React Redux app. 我正在使用React Redux应用程序。 The base template for my React app is something like 我的React应用程序的基本模板类似于

 <div id="react"></div>
 <script type="text/javascript" src="/static/bundles/main-hash.js" ></script>
 <script>
   window.userData = {a: 1, b:2}
 </script>

I want to use the variable userData in my react app. 我想在我的应用程序中使用变量userData window.userData returns undefined at almost all places (reducers, componentDidMount of a component etc.). window.userData在几乎所有位置(组件的reducers,componentDidMount等)都返回undefined。 But if I log the window object, I can see in my console that there is a userData variable in it. 但是,如果我记录窗口对象,则可以在控制台中看到其中有一个userData变量。

To sum it up console.log(window, window.userData) returns - 总结一下console.log(window, window.userData)返回-

Window undefined where Window in which window is a collapsed tree. Window undefined窗口,其中窗口是折叠树的窗口。 Uncollapsing it, the userData variable can be seen in it. 取消折叠,可以在其中看到userData变量。

Please move your script tag before your react component script tag. 请在您的React组件脚本标签之前移动您的脚本标签。 It should work. 它应该工作。

I mean you should create userData member in windows object before you use it. 我的意思是,您应该在使用Windows对象之前创建userData成员。

try this 尝试这个

 <div id="react"></div>
 <script>window.userData = {a: 1, b:2}</script>
 <script type="text/javascript" src="/static/bundles/main-hash.js" ></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM