我目前正在使用react来渲染一个名为prop的道具area
,它看起来像这样:
[{
"id": 1,
"name": "Europe",
"Countries": [{
"id": 1,
"name": "Iceland",
"Cities": [{
"id": 1,
"name": "Selfoss"
}]
}, {
"id": 2,
"name": "Switzerland",
"Cities": [{
"id": 2,
"name": "Geneva"
}]
}]
}, {
"id": 2,
"name": "Asia",
"Countries": [{
"id": 3,
"name": "Japan",
"cities": [{
"id": 3,
"name": "Yokohama"
}]
}]
}]
更新2-
此作品:
class AreaBar extends Component {
constructor(props) {
super(props);
}
.....
renderCountries() {
return(
<div>
This is the country
</div>
)
}
renderContinents() {
return(
<div>
This is the continent
{this.renderCountries()}
</div>
)
}
render() {
return(
<div>
{this.renderContinents()}
</div>
);
}
}
输出:
This is the continent
This is the country
结合地图,这WORKS
renderContinents(area) {
return(
<div>
{area.name}
</div>
)
}
render() {
return(
<div>
{this.props.areas.map(this.renderContinents)}
</div>
);
}
}
输出:
Europe
Asia
但是,当我包含时{this.renderCountries()}
,它什么也不会输出,这就是为什么我无法获得建议的原因。
renderCountries() {
return(
<div>
This is the country
</div>
)
}
renderContinents(area) {
return(
<div>
{area.name}
{this.renderCountries()}
</div>
)
}
render() {
return(
<div>
{this.props.areas.map(this.renderContinents)}
</div>
);
}
}
在Firefox上,这两个大洲都出现了,但是“这是一个没有出现的国家”,但是我看到了
unreachable code after return statement
When an expression exists after a valid return statement,
a warning is given to indicate that the code after the return
statement is unreachable, meaning it can never be run.
好像在说renderCountries永远不能运行。我对此仍然有些困惑,但是我想我将尝试分离这些组件,并查看它是否可以解决问题。
两件事情:
1)在问题的第二段代码中,您正在执行area.countries.map
。area
对象上的键称为Countries
,而不是countries
。area.countries
应该是未定义的。
2)area.Countries
是一个对象数组,就像您在问题中所说的那样。所以是的,您可以在它们上面映射。问题是,每一个Country
都是一个对象,因此,你要渲染的对象为您的孩子<div>
在你的renderCountries
功能。如果只想显示国家/地区的名称,则应执行以下操作:
renderCountries(country){
return(
<div>
{country.name}
</div>
)
}
然后,您将看到一些有意义的输出。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句