我正在尝试将数组呈现为<li>元素的集合。我正在使用React与ES2015语法和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)只是为了检查map是否工作,但仍然会导致相同的错误。
编辑
我试着测试它,发现只有当我使用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"
]
}发布于 2016-07-21 21:07:34
我终于让它开始工作了。只有通过AJAX获取数据时,代码中的问题才会发生,因此,在首次调用函数时,可能已经发生了technologies属性不存在的情况。对我来说,解决方案是在构造函数中的state对象中创建一个空的technologies数组。
Details类的修改构造函数:
constructor(props) {
super(props)
this.state={
"technologies": []
}
}我相信here已经回答了这个问题,但是由于火狐中有不同的错误消息,我找不到它。我希望这个答案对处于类似情况的人有所帮助。
发布于 2016-07-21 18:32:41
这个问题与地图无关。this.props不具备“技术”属性。看看应该将技术数组分配给this.props的任何代码(我不熟悉react)。
https://stackoverflow.com/questions/38511782
复制相似问题