簡體   English   中英

Array.prototype.map返回未定義

[英]Array.prototype.map returns undefined

我試圖將數組呈現為<li>元素的集合。 我正在使用帶有ES2015語法和Babel的React進行翻譯。

該數組存儲在一個對象中,並且可以作為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"
  ]
}

問題與地圖無關。 this.props不具有屬性“ technologies”。 查看應該將技術數組分配給this.props的任何代碼(我對react不熟悉)。

我終於得到它的工作。 我的代碼中的問題僅在我通過AJAX提取數據時發生,因此可能發生了在第一次調用該函數時technologies屬性不存在的情況。 對我有用的解決方案是在構造函數的狀態對象中創建一個空的technologies數組。

修改后的Details類的構造函數:

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

我相信這里已經回答這個問題,但是由於Firefox中出現了不同的錯誤消息,所以我找不到它。 我希望這個答案可以幫助處於類似情況的人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM