
[英]How to access the async/await scope variable out of the async function?
[英]ReactJS access variable out of scope in render function
我有一个配置文件,我想在其中一个组件中导入和渲染/循环播放。 配置文件:
data.config.js
export const data = {
clientData: {
name:'Lynda',
age:'53',
userid:7896
},
otherData: [
{
option1: 'good;',
option2: {type: 'confirmed'},
option3: ['u','g','l','y']
},
{
option1: 'awesome;',
option2: {type: 'temporary'},
option3: ['u','g']
},
],
};
component.js文件
import { data } from '../config/client/data.config.js';
..
var clientData = data.clientData; // console o/p returns object key and values
var otherData = data.otherData; // console o/p returns object key and values
..
render() {
const {
title,
favicon,
socialMediaDesc,
socialMediaImg,
...
} = this.props;
...
return(
<html className="no-js" lang="en">
<title>{title}</title> // works as expectec
...
<script dangerouslySetInnerHTML={{ // eslint-disable-line react/no-danger
__html: `
for (var client in ${clientData}) {
if (${clientData}.hasOwnProperty(client)) {
(function(key, value) {
console.log(key, " : ", value);
})(client, ${clientData}[client]);
}
};
`,
}}
</html>
)
}
预期的控制台输出:
name : Lynda
age : 53
userid : 7896
我得到的结果: Uncaught SyntaxError: Unexpected identifier as value of ${clientData} is [object Object]
如何访问render函数中的clientData和otherData键和值?
您似乎误解了模板字符串是如何工作的。 他们立即创建一个字符串,其中每个${thing}
都被该thing
的字符串值替换。
看看我做类似的事情并只打印字符串时会发生什么。
const clientData = { name: 'Lynda', age: '53', userid: 7896 }; const html = ` for (var client in ${clientData}) { if (${clientData}.hasOwnProperty(client)) { (function(key, value) { console.log(key, " : ", value); })(client, ${clientData}[client]); } }`; console.log(html);
你知道那是怎么回事吗? 由于clientData
是对象,因此它会生成[object Object]
作为字符串的一部分。
如果您确实想危险地生成一些JS(我会极力建议不要这样做),请考虑先生成代码,然后再将其作为HTML注入。
const clientData = { name: 'Lynda', age: '53', userid: 7896 }; let html = ''; for (var client in clientData) { if (clientData.hasOwnProperty(client)) { html += ` (function(key, value) { console.log(key, " : ", value); })(${client}, "${clientData[client]}");`; } } console.log(html);
我想指出的是,除非您做的确实很棘手,否则没有理由将代码包装在<script>
标记中。 照原样运行。 毕竟,您已经在运行一些JS。 也可以立即运行其余部分。
const clientData = { name: 'Lynda', age: '53', userid: 7896 }; for (var client in clientData) { if (clientData.hasOwnProperty(client)) { (function(key, value) { console.log(key, " : ", value); })(client, clientData[client]); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.