【问题标题】:Array.prototype.map returns undefinedArray.prototype.map 返回未定义
【发布时间】:2016-07-21 18:27:29
【问题描述】:

我正在尝试将数组呈现为 <li> 元素的集合。我正在使用带有 ES2015 语法的 React 和 Babel 进行翻译。

数组存储在一个对象中,可以this.props.technologies访问,所以当我写这个的时候:

<ul className="categories">
    { this.props.technologies }
</ul>

我得到以下 html 输出:

<ul class="categories" is="null">
    coffeescript
    atom
</ul>

但是,当我尝试这个时:

<ul className="categories">
{
  this.props.technologies.map(c => {
    return `<li>${c}</li>`
  })
}

我收到一条错误消息:this.props.technologies is undefined

我什至尝试过这样做:

this.props.technologies.map(c => c)

只是为了检查地图是否正常工作,但仍然会导致同样的错误。

编辑

我尝试过测试,发现只有在我使用 AJAX 获取数据时才会出现。

编辑 2 我正在提供一个 MVCE

import React, {Component} from 'react'
import axios from 'axios'

class Header extends Component {

  constructor(props) {
  super(props)
  this.state = {}
  }

  render() {
    return(
      <ul>
      {
        this.props.technologies.map(c => <li>{c}</li>)
      }
      </ul>
    )
  }
}

class Details extends Component {

  constructor(props) {
    super(props)
    this.state={}
  }

  componentWillMount(){
    axios.get(`/static/dummydata/test.json`)
      .then(res => this.setState(res.data))
      .catch(res=>console.log(res))
  }

  render(){
    return(
      <Header technologies={this.state.technologies}/>
    )
  }
}

export {Header, Details}

test.json 中的数据是:

{
  "technologies": [
    "coffeescript",
    "js"
  ]
}

【问题讨论】:

  • 你能分享一下你写的总coe吗
  • 在您的示例中,this.props.technologies 可能不是数组
  • 也许检查技术是否真的是数组或类似数组的对象。例如,您可以通过 Array.isArray(this.props.technologies) 进行操作。
  • @yariash @anvk Array.isArray(this.props.technologies) 返回真
  • @ShubhamKumaram 提供MCVE 然后

标签: javascript arrays reactjs ecmascript-6


【解决方案1】:

问题与地图无关。 this.props 没有“技术”属性。查看应该将技术数组分配给 this.props 的任何代码(我不熟悉 react)。

【讨论】:

  • 技术属性在那里,因为第一个代码 sn-p 运行良好
  • 看起来您已经检查并确定它是一个数组。并且它确实存在。我能想到的唯一另一件事是,在您调用它时它并不存在。当 this.props 没有技术属性时,您可能正在调用 map。
【解决方案2】:

我终于让它工作了。我的代码中的问题仅在我通过 AJAX 获取数据时出现,因此可能发生了 technologies 属性在第一次调用该函数时不存在。对我有用的解决方案是在构造函数的状态对象中创建一个空的 technologies 数组。

Details类的修改构造函数:

constructor(props) {
  super(props)
  this.state={
    "technologies": []
  }
}

我相信这个问题已经回答了here,但由于 Firefox 中出现不同的错误消息,我无法找到它。我希望这个答案对处于类似情况的人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 2019-02-22
    • 2016-11-18
    • 2019-12-24
    • 2016-05-15
    • 2017-03-11
    • 2019-07-09
    相关资源
    最近更新 更多