【问题标题】:Getting a type error from my map function从我的地图函数中获取类型错误
【发布时间】:2020-04-30 13:29:23
【问题描述】:

我正在尝试创建一个仅包含来自 state.words 对象的 id 的数组(如下)

我需要的输出

['word-1','word-2','word-3','word-4','word-5','word-6','word-7']

我的起始数据结构如下所示

words: {
    'word-1': { id: 'word-1', content: 'Jimmy Yukka' ,url:'www.paulayling.me'},
    'word-2': { id: 'word-2', content: 'INXS' ,url:'www.paulayling.me'},
    'word-3': { id: 'word-3', content: 'Up North' ,url:'www.paulayling.me'},
    'word-4': { id: 'word-4', content: 'Prince' ,url:'www.paulayling.me'},
    'word-5': { id: 'word-5', content: 'Magic Moose' ,url:'www.paulayling.me'},
    'word-6': { id: 'word-6', content: 'Salt n Pepper' ,url:'www.paulayling.me'},
    'word-7': { id: 'word-7', content: 'Maddonna' ,url:'www.paulayling.me'}
  }

我遇到的问题是,因为它是一个基于对象数组的方法不会给我我需要的结果,例如下面不起作用 - 但我需要一个对象对象的等价物 我的功能如下


  addNewWord() {
    var currentOrder = this.state.words.map(function (book) {
      return book.id
    })

    console.log('words stuff', currentOrder)
  }

我得到了错误

TypeError: this.state.words.map is not a function

如果相关,则从 componentDidMount() 函数调用该函数

【问题讨论】:

标签: arrays reactjs scope


【解决方案1】:

map 只能用于数组。如果你想列出 words 对象中的键,你可以这样做:

const result = Object.keys(this.state.words);

这将返回您所需的输出

【讨论】:

    猜你喜欢
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多