简体   繁体   English

如何使用reactjs通过window对象将应用程序变量传递到控制台?

[英]How to pass a application variables through window object to console using reactjs?

 window.pageDataLayer.userFeedback.firstName = user ? (user.firstName ? user['firstName'] : '') : '' window.pageDataLayer.userFeedback.lastName = user ? (user.lastName ? user['secondName'] : '') : '' window.pageDataLayer.userFeedback.DOB = user ? (user.DOB ? user['DOB'] : '') : ''

× TypeError: Cannot read property 'userFeedback' of undefined × 类型错误:无法读取未定义的属性“userFeedback”

How to save the application parameters to window objects.如何将应用程序参数保存到窗口对象。

You'll have to create the pageDataLayer -Object first.您必须首先创建pageDataLayer -Object。 Right now you are trying to access the object userFeedback of the object pageDataLayer - which does not exist.现在,您正尝试访问不存在的对象userFeedback的对象pageDataLayer

Also, there is no difference between accessing the user properties with dot-notation or in square bracktes ( user.firstName is the same as user['firstName'] ) so you can omit the duplicate ternary operator there.此外,使用点符号或方括号( user.firstNameuser['firstName'] )访问user属性之间没有区别,因此您可以省略重复的三元运算符。

Lastly, and only in case your user object is on the global scope, you will get an error with your syntax if it does not exist - so you should access it with window as well.最后,只有在您的user对象在全局范围内的情况下,如果它不存在,您将收到语法错误 - 因此您也应该使用window访问它。

So all in all, this should do the trick:总而言之,这应该可以解决问题:

 window.pageDataLayer = { userFeedback: { firstName: window.user ? user.firstName : '', lastName: window.user ? user.lastName : '', DOB: window.user ? user.DOB : '' } } console.log(window.pageDataLayer);

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

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