【发布时间】: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