【问题标题】:.map is not a function in javascript [closed].map 不是 javascript 中的函数 [关闭]
【发布时间】:2020-02-10 06:42:48
【问题描述】:

我一直在尝试在 javascript 中的数组上使用 map 方法,这是我一直在使用的数组的快照。

[
   {"name":"supplier","elements":["beta","gama","alpha"]},
   {"name":"commodity","elements":[]},
   {"name":"year","elements":[]}
]

这是我对地图的使用

function renderTable(entityMap){
  return entityMap.map((lookup,index)=>{
    console.log(lookup)
    const {name, elements} = lookup
    return (
      <tr key={index}>
      <td>{name}</td>
      <td>{elements}</td>
      </tr>
    )
  })
}

而且我知道我使用了正确的数组,因为当我这样做时

console.log(entityMap[1])

它返回{name: "commodity", elements: Array(0)}

更新

我在 render() 中调用了 renderTable 函数

class LookupTable extends Component {
  render() {
    const {
      close,
      saveAndClose,
      entityNames,
      entityModal,
      entityMap
    } = this.props
    console.log(entityMap[1])

    return (
      <Modal 
        title='Add Lookups for entities'
        visible={Boolean(entityModal)}
        onOk={() => saveAndClose()}
        onCancel={() => close()}
        okText='save'
      >
          <div>
            <table>
              <tbody>
              {renderTable({entityMap})}
              </tbody>
              </table>
          </div>

      </Modal>
    )
  }
}


更新 2

Array.isArray(entityMap) 返回 true

【问题讨论】:

  • 可以使用Array.isArray(entityMap)检查是否为数组
  • 你在哪里添加console.log(entityMap[1])?数组是异步填充的吗?这不是minimal reproducible example
  • 您在调用 renderTable {renderTable({entityMap})} 时正在解构数组对象,而是将数组直接传递给 {renderTable(entityMap)}
  • 没有将数组传递给renderTablerenderTable({entityMap}) === renderTable({ "entityMap": entityMap })var tmp = new Object(); tmp.entityMap = entityMap; renderTable(tmp);基本一样。
  • 结论:将数组传递给renderTable,或者从renderTable({entityMap})解构签名。并且调查不要将Array.isArray或更一般的console.log放在随机位置,而是首先放置在错误之前最近的位置(在这种情况下,在return entityMap.map行之前)

标签: javascript arrays json reactjs object


【解决方案1】:

您需要删除调用 renderTable 的大括号,因为 map 方法适用于数组而不适用于对象。

我在需要删除花括号的地方添加了代码,希望对您有所帮助

<tbody>
  {renderTable(entityMap)}
</tbody>

【讨论】:

  • 是的!谢谢我只是没有意识到我不需要再次添加花括号。非常感谢
猜你喜欢
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 2017-08-01
  • 2018-03-10
  • 1970-01-01
相关资源
最近更新 更多