【问题标题】:How to map assosiative array in React/ES6? Starts an infinite loop如何在 React/ES6 中映射关联数组?开始一个无限循环
【发布时间】:2017-12-10 22:30:16
【问题描述】:

数组的生成方式如下:

for(var i = start; i <= end;i+=step) {
    arr[i] = i + 'is the number';
}

数组结构是这样的

arr = [
1100: "1100 is the number",
1101: "1101 is the number",
1102: "1102 is the number",
1103: "1103 is the number",
1104: "1104 is the number",
1105: "1105 is the number",
]; 

等等。

这个数组将被映射到 React 中的一个列表元素中。

render() {
    const list = this.arr;
    const timeList = list.map((element) =>
        <li>{element}</li>
        );


    return (
      <div className="App" >
        {timeList}
      </div>
    ); 

它适用于常规数组,但使用这个会给我一个无限循环。

为什么会发生这种情况以及解决这个问题的可能性是什么?

谢谢

更新: 发现 “如果你使用命名索引,JavaScript 会将数组重新定义为标准对象。 之后,一些数组方法和属性会产生不正确的结果。”

但还是没有解决问题

【问题讨论】:

  • 您的数组结构不是有效的 JavaScript 代码。 “如果你使用命名索引,JavaScript 会将数组重新定义为标准对象。” 这是错误的。每个数组都是一个对象。但是,并非数组的所有属性都被视为数组的元素。因此,很可能您以不应该使用数组的方式使用数组。但是,您拥有的代码不会导致无限循环。如果没有完整的示例,就很难提供帮助。

标签: javascript arrays reactjs ecmascript-6 mapping


【解决方案1】:

我假设您的渲染函数中有 arr 变量。您的问题是“this.arr”。从此处删除“this”并使用“arr”。

这是工作代码,我检查了我的本地反应设置,它打印了数组:

render() {
    const arr = [
         1100: "1100 is the number",
         1101: "1101 is the number",
         1102: "1102 is the number",
         1103: "1103 is the number",
         1104: "1104 is the number",
         1105: "1105 is the number",
     ];
    const list = arr;
    const timeList = list.map((element, idx) =>
        <li key={idx}>{element}</li>
        );


    return (
      <div className="App" >
        {timeList}
      </div>
    );
}

【讨论】:

【解决方案2】:

可能是 i

另一种解决方案是尝试切换到 map() 函数。

请告诉我。

【讨论】:

  • 请不要使用答案来提出澄清问题。
猜你喜欢
  • 2018-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 2011-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多