ReactJS访问变量超出了渲染功能的范围

时间:2017-08-28 18:55:52

标签: javascript reactjs scope jsx

我有一个配置文件,我想在我的一个组件中导入和渲染/循环。配置文件:

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>
  )

}

预期的控制台o / p:

name  :  Lynda
age  :  53
userid  :  7896

我得到的结果:Uncaught SyntaxError: Unexpected identifier as value of ${clientData} is [object Object]

如何在render函数中访问clientData和otherData键和值?

1 个答案:

答案 0 :(得分:1)

您似乎误解了模板字符串的工作原理。它们会立即创建一个字符串,其中每个${thing}都被thing的字符串值替换。

查看我做类似事情时会发生什么,然后打印字符串。

&#13;
&#13;
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);
&#13;
&#13;
&#13;

你看这是怎么回事?由于clientData是一个对象,因此它会生成[object Object]作为字符串的一部分。

如果你真的想要危险地生成一些JS(我会彻底建议反对),那么考虑生成代码然后将其注入HTML。

&#13;
&#13;
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);
&#13;
&#13;
&#13;

我想指出,除非您做了一些非常棘手的事情,否则没有理由将该代码包装在<script>标记中。按原样运行它。毕竟,你已经在运行一些JS了。也可以马上运行其余部分。

&#13;
&#13;
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]);
  }
}
&#13;
&#13;
&#13;